Lectures: Monday, 12:20, S4 (Pavel Ježek)
Labs: Thursday, 14:00, SU2 (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
- Course introduction, exam
- Differences in representation of variables in memory layout in Python, C++ and C# languages
- Differences between reference and value types, passing arguments by value
- Memory overhead of reference types, class
Type
record (class)
,record struct
Materials
2. lecture
- Reminder of the difference between reference and value types, decided at type declaration
- Examples of typically reference or typically of value types
- Implicit typed variables (
var
),new
without type name in the context where it is obvious (parameter, declaration) - Fields vs. properties in types,
readonly
- Automatically implemented properties
- Allocation on the GC heap, zeroing memory, constructors, initializers
init
property setters (C#9),required
keyword (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),.ctor
- 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
- Static fields and a class (static) constructor,
.cctor
- Delegation of constructor via
: this()
, the order of initialization - Different variants of constant values,
readonly static
,const
, constant-folding by compiler for initializations ofconst
values, constant-folding by JIT for simple functions - Underscore (
_
) in integral literal enum
,ToString
method,[Flags]
attribute
6. lecture
- Introduction to attributes (
*Attribute
class),nameof
operator - Additions to
enum
and attribute[Flags]
,enum.Parse
,enum.ToString
- Introduction to NuGet packages
- (Nicro)benchmarks and BenchmarkDotNet
- JIT optimization, different JITs (Tiers)
- Function translation (prologue, body, epilogue), method inlining
System.Runtime.CompilerServices.MethodImpl
,MethodImplOptions
- micro-optimization
- Calling methods
- covering the methods in the inherited class with the keyword
new
, selecting the method during compilation (generating thecall
instruction) - virtual methods (
virtual
),override
, virtual method table (inType
), call method at runtime (instructioncallvirt
)
- covering the methods in the inherited class with the keyword
Materials
7. lecture
- Hiding members in a inherited type (keyword
new
), warning vs. error - Syntactic notation of virtual methods in C++, C# and Java and problems with default virtual methods in Java
- Optimization of virtual call (devirtualization),
sealed
types,sealed override
methods - Virtual method table, interface method table and implementation of interface by virtual method
- Difference between
interface
andabstract
class interface
extending another interface and the problem of diamond inheritance- Reasons for explicit
override
in C# versus implicit in C++ base
keyword for generating non-virtual call from ancestor
Materials
8. lecture
- Alternative to non-virtual calling from ancestor (cannot be done using
base
) - Calling virtual methods in the constructor
- Stardew Valley game and Factory design pattern
- Generating
callvirt
instruction even when calling non-virtual methods - Reminding of automatically implemented properties (with backing field)
- General properties,
get
,set
, contextual keywordvalue
, methodsget_*
,set_*
- Expression-bodied members (function
=>
body) for functions, but also for properties and syntactic difference from lambda expressions - Differences between property and function, speed requirements for properties, naming conventions
- virtual and abstract properties and properties as API in
interface
, static properties double.NaN
instead ofdouble?
and comparison usingdouble.IsNaN
- visibility of class members (
public
,protected
,private
,internal
,protected internal
,private protected
,file
) and implicit visibility at declaration - Variable declaration/allocation, variable lifetime, JIT optimization, lifetime limitation using
{
and}
Materials
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
Materials
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
Materials
Recommended Literature
- Joseph Albahari: C# 12 in a Nutshell: The Definitive Reference, O’Reilly Media, 2023 (i.e. on Amazon UK)
- Jon Skeet: C# in Depth (4th Edition), Manning Publications, March 2019 (i.e. on Amazon UK)
- C# Language Specification version 8
Alternatively
- 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)
- 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 differences between reference and value types, sizes of variables and instances, alignment/padding, arrays, allocation and layout on heap
- For next week
- (5 points) Word Counting
- (5 points) Word Frequency
2. practicals
- Key aspects of the solution (general)
- functional (within specification)
- effective (within use)
- nice (maintainable, extensible, documented)
- Reading words:
File.ReadAllText
(not enough separation of where the data is and how the data is read)
- Where is the data:
File.OpenText
ornew StreamReader
(orConsole.In
,StringReader
), asTextReader
(and as a counterpart relation betweenStreamWriter
,StringWriter
,Console.Out
asTextWriter
)
- How are they read?
- ✖
ReadToEnd
(problem with large files) - ✖
ReadLine
(possible problem with long lines) - ✔
Read
(by characters; note that the function returnsint
) - the difference between splitting words (
string.Split
and the variant withStringSplitOptions.RemoveEmptyEntries
) and composing words (string += char
, respectivelyStringBuilder
)
- ✖
- More top-down approach (without technical details)
- some
WordReader
that can pullstring
as words fromTextReader
- some
WordProcessor
(WordCounter
,WordFrequencyCounter
) that can take astring
as a word and process it (and maybe arrange the output somehow) - some common part (arguments, errors, connections), demonstrated on LineCounter
- some
- Assignment of new tasks Paragraph word count (and input) and To sum, or not to sum (input and output)
- Additional videos:
- xUnit testing framework, integration with VS, creating projects, project reference, writing tests, integration tests,
Assert
- xUnit testing framework, integration with VS, creating projects, project reference, writing tests, integration tests,
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
) (contract, values) - 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 week
- (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 points) improve your solutions of Paragraph Word Counting and To count, or not to count (will be useful for next assignment)
4. practicals
- Different ways of representing user roles in the application
- Using implicit
Type
and object hierarchy, with data and without data - Using
enum
s, example - Using the explicit
Role
class, example - Using a more complex object hierarchy, example
- Using interfaces, example
- Discussion about efficiency, clarity, use of individual approaches, control during runtime, during translation
- Using implicit
- Implementation of
Token
andTokenReader
, design pattern Decorator/Wrapper, debugging messages using design pattern decorator - Different approaches to check if the character is whitespace and speed differences
ITokenProcessor
which can process all kinds of tokens sounds like a good idea, but it leads to a bad design and a cumbersome implementation- For next week: (8 points) Text justification
- +3 points for integration tests submitted after the solution
- +5 points for integration tests submitted before the solution (and the solution then passes reasonably well)
5. practicals
- GC, memory-leak in C# and how to resolve that
string
is immutable, mutable variantStringBuilder
- Difference between
" "
and' '
to represent space character (in memory and when used in method acceptingstring
vs.char
) - Banning usage of features from
System.Linq
(LINQ will be explained in the summer semester) - Coding conventions, names of identifiers, Example
- recoverable vs. unrecoverable errors, difference in identification of the error and it’s presentation to the user/developer
- custom error types, with data
- Description of architecture to solve first four assignments `WordProcessingToolkit`
- custom
ApplicationException
andAppErrorHandler
, extendedTableSummatorAppErrorHandler
,IProgramCore
ArgsToIOState
a conversion from system exceptions to application exceptionstry
,finally
(IDisposable
some other time)
- custom
- Differences between integration and unit tests
- Testing methods accepting a contract, Fake/Mock contract, demonstrated on `LegacyWordCounterApp`
- For next week
- Deadline extension for Text justification (possible maximum of points reduced to 7)
- (5 points) Unit test
ParagraphDetectingTokenReaderDecorator
class and fix bugs in the implementation - (5 points) Refactor
TableSummatorProcessor
, so that it can be unit tested and write unit tests for part of it
6. practicals
- Virtual methods, interface methods,
abstract
, example LegacyWordCounter
and refactoring forFileProcessingConsoleAppFramework
IWordReader
toITokenReader
from last week- we need
WordCounter
asITokenProcessor
, but it isIWordProcessor
, but we don’t want to modify the (functional, tested) implementation => design pattern Adapter, TokenProcessorFromWordProcessorAdapter
- TestDrivenDevelopment
- ChatGPT unit tests on
int.Parse(string)
(insufficient), example - Comments on
ParagraphDetectingTokenReaderDecorator
unit tests - Comments on
TableSummator
some other time - For next week
- 1. (micro)benchmark using Benchmark.NET to compare different approaches to the
Dictionary
data structure in the context of the Word Frequency assignment, approaches - 2. (micro)benchmark using Benchmark.NET to compare the use of
SortedList
,SortedDictionary
andDictionary
+Sort
data structures in the context of the Word Frequency assignment - for solving up to 8 points manually in ReCodEx
- 1. (micro)benchmark using Benchmark.NET to compare different approaches to the
7. practicals
- Example on IMT and VMT and solution
- Comments on the Word Frequency Task Benchmarking, Project and Results
- Scenario for modifying an existing word in
Dictionary
- Scenario for adding a new entry to
Dictionary
and ways to measure it (and not measure something else like key allocation or data structures),[IterationSetup]
andManualConfig
- Discussion of the complexity of data structures and conclusions of benchmarks
- Scenario for modifying an existing word in
- .NET source codes as repository or as browser
- For next week
- (5 points) Play a DynaBlaster game, analyze screens in BATTLE mode and draw a graph where vertices are different screens, edges represent possible transitions between screens, and edge values are data that flows between screens
8. practicals (only offline)
- Comments on Dynablaster’s screens next time
- Complementary website about extending lecture’s implementation of Stardew Valley game, Example following several iterations of thoughts
- For next week
- (5 points) Multifile text justification in ReCodEx + (5 points) for unit tests for new features
9. practicals
- Comments on solving the Block Alignment task
- Splitting into
ParagraphFormattingProcessor
andILineJustifier
- One implementation of
ILineJustifier
, Example - Splitting into two implementations of
BlockJustifier
andLeftJustifier
, Example - Splitting will allow us to configure the alignment type at the
ParagraphFormattingProcessor
instance level — According to the assignment (and output), All left (and output) or All to block (and output). (Input is aligned to 35 characters)
- Splitting into
- Comments on the solution to the task Multi-file alignment (from the solution to the original task, ideally without the need to delete existing code)
ISimpleStringWriter
(as an alternative to theTextWriter
implementation),SimpleStringWriterToTextWriterAdapter
,HighlightingStringWriterDecorator
LazyMultiSourceTokenReader
,ITokenReaderFactory
,EmptyTokenReader
- Comments on the solution to the task Dynablaster and discussion of a possible implementation
- Model-View-Controller (MVC) design pattern
- For next week
- (10 points) Online bookstore using MVC design pattern
10. practicals
- Examples for practicing tracking references: Assigning value types (and solution), reference types (and solution), passing references
- Heartbleed bug in OpenSSL
- Comments on the Internet Bookstore solution, discussion, possible solutions
- Basic solution
- More advanced solution (more separated and using abstract factory to return individual views)
- For next week
- (10 points) Huffman I: The tree needs to be stored in memory in some object representation. It is not enough to print it gradually.
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: 11. 7. 2025
- Demonstration of the final (fully functional, according to the specification) version of the application, including both user and development documentation.
-
- deadline: 8. 8. 2025
-
- deadline: 5. 9. 2025
-
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
- 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 the 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.
ATTENTION! Personal presentation is part of submission. For the demonstration, prepare some form of presentation where you show the main functions of the program + the main problems solved + an outline of the architecture.
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 90p 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 |
---|---|
110+ | +1.25 strong points |
130+ | +2 strong points |
160+ | +2 strong, +0.5 weak points |
210+ | +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: Homework is an independent work, the aim of which is to evaluate the student’s ability to independently develop a more complex program in the C# language. If a student is found to have submitted a different solution (e.g. several students submitted different instances of the same solution to a homework assignment, etc.), this will be considered attempted cheating. All such students will not complete the subject NPRG035 in this academic year and lose the possibility of recognition of completed obligations in the next year; eventually, the disciplinary committee of the UK MFF will be recommended to exclude them from their studies!
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!