Lectures: Tuesday, 15:40, S9 (Pavel Ježek)
Labs: Wednesday, 9:00, SW2 (Filip Kliber)
Page in SIS: NPRG035
Grading: Credit and exam
Table of contents
- Lectures outline
- Practicals outline
- Information about the Exam
- Requirements for the Credit
- Acknowledgement of requirements from past years
[in Czech] Zde jsou informace pro studenty anglické paralelky předmětu Programování v jazyce C#. Pro českou si v záhlaví stránky přepněte jazyk do češtiny.
Lectures outline
1. Lecture
- Introduction to the course, exam
- Differences in memory representation of variables in Python, C++ and C# languages
- Differences between reference and value types, passing arguments by values
- Memory overhead of reference types, a
Type
class record (class)
,record struct
2. Lecture
- Reminder of differences between reference and value types, specified at the point of type declaration
- Examples of typical reference, resp. typical value types
- Implicitly typed variables (
var
),new
without the name of the type in context where it makes sense (parameter, declaration) - Fields vs. properties in types,
readonly
- Automatically implemented properties
- Allocation on GC heap, nulling of memory, constructors, initializers
init
setters for properties (C#9), keywordrequired
(C#11)- Primary constructor for
record class
andrecord struct
- Nullable value types,
is null
operator
3. Lecture
- Reminder of nullable value types
null
in runtime of .NET (CLR) and accessingnull
leading toNullReferenceException
- Nullable reference types (C#8)
- Duck typing in Python, dynamically typed languages
- Interface in C#, interface table
I
within a typeA : I
and finding a method by tracking several pointers in situation likeI i = new A(); i.m1();
- Hiding base methods via
new
keyword and finding a correct method that will be called - The
is
operator andInvalidCastException
, including the more recent variantvariable is Type newVariable
- Properties (not fields) as part of the contract in interface
4. Lecture
- Non-portability (dependency on platform) of compiled C++
- Solving the portability by universal executable (fat binary) on MacOS
- Compilation of C# code (
csc.exe
) into (portable) assembly (.dll) to be later JIT (Just in time) compiled on specific platform - Optimization options of JIT or AOT (Ahead of time) compilation
- CIL (Common intermediate language), metadata in assembly
- Running of C# programu using
dotnet
command and via compiled.exe
(windows only) ildasm
(part of .NET SDK) ailspy
(standalone) tools, debugging information (.pdb
file)- Inheritance in C#, calling instance methods (hidden
this
parameter) - Abstract class, common ancestor
object
, calling a constructor of parent usingbase
is
operator,Type
type,GetType()
method andtypeof
operator
5. Lecture
- Constants
readonly
,readonly static
,const
- Optimizations of the compiler for
const
, constant on the CIL level const
for basic types andstring
- Class (static) constructor,
.cctor
- Delegation of constructor via
: this()
, the order of initialization - Zeroing the memory before calling the constructor thanks to GC
nameof
keyword, underscore (_
) in numeric literalenum
,System.Enum
,ToString
method,[Flags]
attribute,enum.Parse
using
alias andstruct
as an alternative toenum
6. Lecture
- introduction to NuGet packages
- (micro)benchmarks a BenchmarkDotNet
- introduction to attributes (
*Attribute
class) - JIT optimizations
- Compilation of a function (prolog, body, epilog), method inlining
System.Runtime.CompilerServices.MethodImpl
,MethodImplOptions
- micro-optimizations
- Call of methods
- method hiding in inherited class using the
new
keyword, choosing the method at compile-time (generating acall
instruction) - virtual methods (
virtual
),override
, virtual method table (inType
), call the method at runtime (callvirt
instruction)
- method hiding in inherited class using the
7. Lecture
- Hiding members in derived class (
new
keyword), warning vs. error - Syntax of writing virtual methods in C++, C# and Java languages and issues with by default virtual methods in Java
- Optimizations of virtual call of
sealed override
methods andsealed
types (devirtualization) - Virtual method table, interface method table and calling through the interface
- Difference between
interface
andabstract
class interface
extending different interface and diamond problem with multiple inheritance- Reasons for explicit
override
in C# in comparison to implicit one in C++ base
keyword to generate non-virtual call from a parent class
8. Lecture
- Calling virtual methods in constructor
- Stardew Valley game and Factory design pattern
- Generating
callvirt
instruction for calling non-virtual methods - Reminder of automatic implemented properties (with a backing field)
- Properties in general,
get
,set
, contextual keywordvalue
,get_*
,set_*
methods - Expression-bodied members (method
=>
body) for methods and properties - Differences between methods and properties, expectations in performance, naming conventions
double.NaN
insteaddouble?
and comparison viadouble.IsNaN
- virtual and abstract properties and properties as API in
interface
, static properties - Differences between different syntaxes for writing properties and methods including the expression-bodied members
- Side-effects in properties
- Visibility of class members (
public
,protected
,private
,internal
,protected internal
,private protected
,file
) a implicit visibility for declaration - Declaration/allocation of a variable, lifetime of variables, JIT optimizations, limiting lifetime via
{
a}
9. Lecture
- Hiding fields of a class (
new
keyword) and hiding local variables in C++ (in more nested scope), but not in C# - Necessity of initialization of local variables before reading, initialization in pattern-matching syntax, explicit scope
- Reminder of value and reference types, references, boxing, calling methods on boxed instance, unboxing and explicit conversions,
InvalidCastException
, compatibility withobject
- function with variable amount of parameters and
params
keyword - unsupported combination of unboxing and other cast and workaround using multiple (explicit) conversions
- boxing of nullable value types
- pointers, do not use
- tracking reference, example with archaic C++/CLI language
10. Lecture
- Reminder of tracking references and problems with general tracking references, necessity of inicializace of tracking references
ref
parameters, automatic dereference, tracking reference on variable of reference type, necessity of repeated keyword use at call siteout
parameters, necessity of writing into parameters, possibility of passing uninitialized variable, declaration of variable directly in the parameter- discard variable underscore (
_
), only if current context has no identifier named_
, discarding of the result of assignment operator in
parameters and possibility of implicit references (for micro-optimization purposes), ref readonly parameter- tracking reference as local variables or as return value
interface
outside of type system (not derived fromobject
), but possibility of callingobject
methods directly oninterface
variable- Why is
struct
implicitlysealed
and solution in C++ - Calling methods of structures with hidden
this
parameter declared as tracking reference struct
implementing aninterface
and problems with boxing
Recommended Literature
- Mark Michaelis with Eric Lippert: Essential C# 5.0, Addison-Wesley, 2013 (i.e. on Amazon UK)
- Jeffrey Richter: CLR via C# (4th Edition), Microsoft Press, December 2012 (i.e. on Amazon UK)
- Jon Skeet: C# in Depth (3rd Edition), Manning Publications, September 2013 (i.e. on Amazon UK)
- blog Erica Lipperta (former member of Microsoft’s C# team): Fabulous Adventures In Coding
- C# Language Specification 7.0
Alternatively
- Christian Nagel, Evjen, Jay Glynn, Karli Watson, Morgan Skinner: Professional C# 4.0 and .NET 4, Wrox, John Wiley & Sons, March 2010 (i.e. on Amazon UK
Practicals outline
1. Practicals
- Introductory lecture, credit requirements (also available on this very page), concept of practicals
- IDE: Visual Studio, where to get and alternatives
- Practicing difference between reference and value types
- sizes of variables and instances, alignment, array
- New homeworks Word Counting a Word Frequency
2. Practicals
- Key aspects of the solution (in general)
- functional (with respect to the specification)
- effective (with respect to the use case)
- beautiful (reusable, maintainable, extensible, self-documented)
- Reading words:
File.ReadAllText
(insufficiently separated concepts of where is data and how to read data)
- Where is data:
File.OpenText
ornew StreamReader
(and possiblyConsole.In
,StringReader
), asTextReader
(and on a contrary,StreamWriter
,StringWriter
,Console.Out
asTextWriter
)
- How to read?
- ✖
ReadToEnd
(problem with large files) - ✖
ReadLine
(problem with lengthy lines) - ✔
Read
(by characters; care that the function returns anint
) - difference between splitting words (
string.Split
and variant withStringSplitOptions.RemoveEmptyEntries
) and concatenating words (string += char
, resp.StringBuilder
)
- ✖
- More of a top-down approach (without technical details)
- some
WordReader
, that can retrieve words asstring
fromTextReader
- some
WordProcessor
(WordCounter
,WordFrequencyCounter
), that can processstring
as a word (and possibly take care of output) - some common part (arguments, errors, how to combine the code), demonstrated on LineCounter
- some
- New assignments Paragraph Word Counting a To count, or not to count
- Just vague description, without technical details, so decomposition can be decided and thought about
- Published in ReCodEx with a delay, but with standard one-week deadline
3. Practicals
- Deadline extension for Paragraph Word Counting and To count, or not to count
- Reminder of
interface
as specification of a contract and examples - Contract directly in a form of a type (and a difference to python duck-typing)
- Contract using an enumeration type (
enum
) and examples - Discussion about possible object-oriented design of first four assignments
interface IWordReader
and implementationWordReaderByLines
,WordReaderByClass
interface IWordProcessor
and implementationWordCounter
,WordFrequencyCounter
,ParagraphWordCounter
,TableSummarizer
- glue-code to connect those by using the interfaces
- What methods should
IWordReader
have, what is their return type, what parameters, where to read words from? - What methods should
IWordProcessor
have, what is their return type, what parameters, where to write output to? string
vs.string?
vs.Token
- For next practicals
- (4+4 points) fix your solutions of Paragraph Word Counting and To count, or not to count (if it didn’t pass all tests in ReCodExu)
- (5+5 points) submit integration tests in xUnit, nUnit or MSTest framework (at least 10 test scenarios per assignment)
- (0+0 bodů) improve your solutions of Paragraph Word Counting and To count, or not to count (will be useful for next assignment)
4. Practicals
- Operator
is
and how it works - Different ways to represent a role system of users in the application
- Via implicit
Type
and class hierarchy, with data and without data - Via enumeration (
enum
), example - Via explicit
Role
class, example - Via complex class hierarchy, example
- Discussions about effectivity, readability, usage of different approaches, error checking at runtime or compile time
- Via implicit
- Implementation of
Token
andTokenReader
, design pattern Decorator/Wrapper, debug messages by decorator pattern, different alternatives of refactoring done by ChatGPT, examples - Different ways to check if character is whitespace
ITokenProcessor
capable of processing all kinds of tokens sound like a good idea, but leads to bad design and chaotic implementation- New assignment Text justification
- Extra points for integration/unit tests, more extra points if tests are submitted before the solution
- Importance of picking good names for tests (not
UnitTest17
, but ratherSingleParagraph_LongLines_SimpleWhitespaces
)
5. Practicals
- GC, memory-leak in C# and ways to fix it
string
being immutable and mutableStringBuilder
variant- difference between
" "
and' '
as a representation of space (memory-wise and usage-wise in the context of methods acceptingstring
vs.char
) - Ban of usage features from
System.Linq
(more about LINQ in summer semester) - Coding style and naming conventions
- recoverable vs. unrecoverable errors, difference between identification of an error and it’s presentation to the user/programmer
- custom types for errors, with data
- Description of solution of `WordProcessingToolkit`
- custom
ApplicationException
andAppErrorHandler
, extendedTableSummatorAppErrorHandler
ArgsToIOState
and conversion of system exceptions to application exceptionstry
,finally
(more aboutIDisposable
some other time)
- custom
- Experiment, Bug finding tale
- Differences between integration tests a unit tests
- Testing a method that requires a contract, Fake/Mock contract, example in `LegacyWordCounterApp`
- For next practicals
- Extending the deadline of Text justification
- (5 points) Write unit tests for
ParagraphDetectingTokenReaderDecorator
and fix bugs in implementation - (5 points) Refactor
TableSummatorProcessor
, such that it can be unit tested and write unit tests for some part of the implementation
6. Practicals
- Virtual methods, interface metods,
abstract
, example LegacyWordCounter
and refactoring forFileProcessingConsoleAppFramework
IWordReader
toITokenReader
already done- we need
WordCounter
asITokenProcessor
, but it isIWordProcessor
and we don’t want to modify (working, tested) implementation => Adapter design pattern
- TestDrivenDevelopment
- ChatGPT unit tests for
int.Parse(string)
(insufficient), example - Comments for unit testing of
ParagraphDetectingTokenReaderDecorator
- Comments for
TableSummator
some other time - For next practicals
- 1. (micro)benchmark via Benchmark.NET to compare usage of different data structures —
SortedList
,SortedDictionary
andDictionary
+Sort
— in the context of Word Frequency assignment - 2. (micro)benchmark via Benchmark.NET to compare different approaches in accessing
Dictionary
in the context of Word Frequency assignment, approaches - It is more natural to do assignments in order 2. -> 1. You can get up to 8p in ReCodEx assigned manually
- 1. (micro)benchmark via Benchmark.NET to compare usage of different data structures —
7. Practicals
- Comments for refactoring
TableSumatorProcessor
into a better unit testing design- Separation into independent
HeaderProcessor
DataColumnSumator
,TableSumatorProcessor
classes with well defined input and output - Passing data using public API of the classes and not by passing the classes directly
- Separation into independent
- Comments for Benchmarking the Word Frequencies assignment
- Scenario when modifying existing word in
Dictionary
- Scenario when adding new word to the
Dictionary
and different approaches how to measure just that and nothing else (such as allocation of keys or the data structure),[IterationSetup]
aManualConfig
- Source code of .NET as repository or as a browser
- Discussion about complexity of data structure and summary of the benchmarks
- Scenario when modifying existing word in
- ToDo: Introducing the factory design pattern on Stardew Valley game
- Adding new fruit as
abstract class Fruit
vs.interface IFruit
andinterface IEatable
- NoseGrowingAppleTree and Abstract factory design pattern
- Even further separation of concepts and Strategy design pattern
- Adding new fruit as
- For next practicals
- (5p) Multi-file text justification in ReCodExu + (5p) Unit Tests
- (5p) Play the game called DynaBlaster, analyze screens in BATTLE mode and draw a graph where vertices are different screens, edges are possible transitions between screens and values of edges symbolize the data that flow between the individual screens
8. Practicals
- Example for IMT and VMT and solution
- Comments on the solution to Text Justification assignment
BlockJustifier
,LeftJustifier
- Comments on the solution to Multifile text justification assignment (from the original solution, ideally without a need to remove existing code)
ForwardingStringWriterAdapter
,HighlightingStringWriterDecorator
,TokenReaderFactory
- Comments on the solution to Dynablaster assignment and discussion about possible implementation
- Model-View-Controller (MVC) design pattern
- For next practicals
- Bookstore eShop in ReCodExu by using the MVC pattern
9. Practicals
- Heartbleed bug in OpenSSL library
- Comments on solving the Bookstore eShop assignment, discussion, possible solutions
- Basic solution
- Advanced solution (more separated and using abstract factory design pattern to return views)
- New assignment Huffman I
- It is necessary to store the tree in memory in some data structures.
10. Practicals
- Comments on Huffman I assignment
- Where to focus on performance (reading the file or building the tree)
- Difference between
BinaryReader
andFileStream
, internal implementation details and more efficiency using custom buffer (of size 2n) - Approaches to counting frequencies:
Dictionary<byte, long>
vs.new long[256]
(int
is not large enough for 1TiB file) - Representation of
HuffmanTree
: přímočarý přístup or more OOP
- New assignment Huffman II
- Bit operations in C#: or
|
, and&
, xor^
, not~
, left shift<<
right shift>>
(>>
is dependant on the signed-ness of the types) BinaryWriter
BitConverter
,byte[] GetBytes(int)
,GetInt32(byte[])
, …
- Bit operations in C#: or
11. Practicals
- Comments on Huffman II assignment
- Again, where to focus on performance (reading the file vs. building the tree vs. 2nd reading the file vs. writing the file)
- Storing the bit sequences
- ✖
string
("1011" + "0"
) allocates new memory for every concatenation and copies characters from two strings - ✖ Converting
string
tobyte
usingConvert.ToByte("10110", 2)
is general algorithm (supports more bases than just binary) - ✔ Bitwise operators (or
|
, and&
, xor^
, not~
, left shift<<
right shift>>
)
- ✖
- Setting n-th bit of
value
to 1 asvalue | x
, where binary representation ofx
has all zeros except one1
on n-th position (i.e. some power of two)- ✖
Math.Pow(2, x)
general function for powering, supporting floating point types (i.e. general algorithm, not optimized for powers of two) - ✔
1 << x
- ✖
- Un-setting n-th bit (setting it to 0)
value
asvalue & x
, where binary representation ofx
has all ones, except one0
oon n-th position, which is negation of a power of two.value & ~(1 << n)
- Caching codes vs. repeated tree traversal
- verbatim identifier (
byte @byte
void @while()
) for interacting with s .NET language L with identifier that is keyword in C#, but not in L - digit separator in numeric constant to improve readability (i.e.
int price = 12_751;
orulong bits = 0b10110010_10010101
) - New triplet of Excel assignments (level 0, level 1, level 2)
- Do not evaluate on the fly, but load the list, then evaluate, then write out
- Do not attempt to support evaluation of different types than int (i.e.
double
orstring
) - Do not attempt to support different kinds of formulas (functions, more operators, constants)
12. Practicals
- Hints and notes for the Excel assignment and prolonging the deadline by one more week.
- Memory issues and where to get more test data
- Excel experiment and debugging
- C#
readonly
as an alternative to C++const
function, example - Bug in Log4j library in Java
- More ideas for Excel, fast-fail parsing, exceptions issues, horner’s method for parsing references instead of
int.TryParse
- New assignment Expression Evaluation
- Parsing the expression and evaluation, basis of an expression library
- New operator types, but not new value types (
string
,double
), possibly variables - Evaluation via recursion
- 5b for some solution + 5b for reasonable design
Information about the Exam
Primary part of the exam consist of written part including around 6 to 8 questions (which might include sub-questions). Every question has a visible maximal amount of points that can be awarded for the question (=N
). For correct answer, the student will receive N
points for the question; for incomplete, but overall good answer (i.e. some part of the answer is missing or is incorrect), the student will receive 0.5 * N
points; in other cases, the student will receive 0
points (i.e. if the answer is missing completely or is mostly incorrect).
The student can receive up to 10
points from the Exam. The mapping between points and grade is as follows:
Points from the exam | Awarded grade |
---|---|
10 – 8.5 | 1 |
8 – 6.5 | 2 |
6 – 5 | 3 |
4.5 – 0 | 4 |
The written part of the exam takes up to 150 minutes (i.e. 20 minutes for each question, with 30 minutes extra time). After the written part, the oral part follows, where the examiner discusses the answers with the student, demands clarification when needed and asks complementary questions if deemed necessary — based on this, the final amount of points for each question is determined. The evaluation is always based on written part of the Exam, which means that student can’t be awarded with more than 0 points for a question without an answer.
For illustration, here follows a list of some exams from previous years:
- 1.2.2021 (PDF)
Requirements for the Credit
In order to receive the credit, it is necessary to fulfill three requirements:
1. Practical Test
Fully implement a simple task within a 3 hour time limit. Takes place during the examination period in computer lab. You have five attempts to complete the test in total, but you can attempt the test only three times during the winter (you can take other two in summer examination period).
2. Final Project
Deadlines:
- Specification: 12. 7. 2024
- Demonstration of the final (fully functional, according to the specification) version of the application, including both user and development documentation.
-
- deadline: 9. 8. 2024
-
- deadline: 6. 9. 2024
-
You can use single project to complete several courses about C# and .NET, if the project is complex enough:
- Requirements for NPRG035:
- Demonstrated before the 1. deadline: 30kB of source code written in the C# language
- Demonstrated after the 1. deadline: 45kB of source code written in the C# language
- Demonstrated after the 2. deadline: 60kB of source code written in the C# language
- Requirements for NPRG035 + NPRG038, Advanced .NET Programming II:
- Demonstrated before the 1. deadline: 45kB of source code written in the C# language
- Demonstrated after the 1. deadline: 60kB of source code written in the C# language
- Demonstrated after the 2. deadline: 90kB of source code written in the C# language
Source code is the code you (and only you) wrote in C# language. Comments are included, but everything has to be reasonable.
Final Project for Advanced C# Programming require additional (nontrivial) usage of features and techniques taught during lectures of that course.
If the application has nontrivial graphical interface, you can use it to get credit for Programming User Interfaces in .NET as well.
Please prepare few slides (talk) about your application’s main features, problems you faced and overall design overview.
3. Homeworks
There will be several small homeworks assigned during the semester. If you complete a homework you will get points (10p usually). You are required to obtain at least 80p from the homeworks. By having more points from homeworks, you can get some extra points to the exam test.
Points from HW | Bonus to the exam |
---|---|
100+ | +1.25 strong points |
120+ | +2 strong points |
150+ | +2 strong, +0.5 weak points |
200+ | +2 strong, +1 weak point |
Strong points only work during the first attempt on the exam. Weak points can not change the result of the exam from 4 to 3.
Homeworks will be assigned using the ReCodEx system. You will also submit your solutions to this system and they will be automatically graded. The usual deadline will be 7 days. You can also gain some extra points if your solution is well-designed, has relevant comments present or has other aesthetic features that the system can’t grade.
Note: Homeworks are strictly individual.
Acknowledgement of requirements from past years
If the student was enrolled in this course during the last academic year and fulfilled only some of the requirements for the credit, the teacher can, upon student’s request, acknowledge the fulfillment of requirement from the last year (attendance, homeworks, Practical Test or Final Project). The topic (specification) of Final Project does not need to be acknowledged by new teacher. If the student succeeded in the exam, but didn’t receive the credit, it is possible, upon student’s request, acknowledge the result of the exam. This is a good will of teachers of this course and students can’t enforce this on study department!