3. Creating Types In C# || C# 10 Flashcards

1
Q

What is a ‘field’?

A

A field is a variable that is a member of a class or a struct:
~~~
class Octopus
{
string name;
public int Age = 10;
}
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Describe readonly modifier

A

The readonly modifier prevents a field from being modified after construction. A read-only field can be assigned only on its declaration or within the enclosing type’s constructor.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Describe a constant

A

A constant is evaluated statically at compile time and the compiler literally substitutes its value whenever used
A constant can be any of the built-in types or an enum type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Name a difference between readonly field and a constant

A
  1. Initialisation:
    A. Read-only field can be initialised without an assigned value. Default value will be assigned automatically.
    B. Constant must be initialised with a value.
  2. Field can be of any type, while constant must be only of built-in or enum type.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is a method?

A

A method performs a series of statements. A method can receive an input data from the caller by specifying a parameters, and an output data by specifying a return type or a void type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is method’s signature?

A

A method’s signature comprises its name and and parameters types in order (but not the parameters names, nor return type)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is a expression-bodied method?

A

Instead of :
int Foo(int x) { return x*2; }
Use:
int Foo(int x) => x*2;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is static local method?

A

Local method is a method within a method. And adding a static modifier prevents it from seeing local variables and parameters of enclosing method from any accidental reffering to them.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is a constructor?

A

Constructors run initialization code in a class or struct. A constructor is defined like a method, except that the method name and return type are reduced to the name of the enclosing type

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is constructor overloading? How it is written?

A

One constructor can call another constructor using ‘this’ keyword:
public Wine (decimal price, int year) : this(price) {Year= year;}
In this scenario second constructor is executed first

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is a deconstructor?
Describe syntax

A

Deconstructing method act as an opposite of constructor- assigns fields back to a set of variables
Deconstruct method must be called Deconstruct and have one or more out parameters
~~~
public void Deconstruct (out float width, out float height)
{
width= Width;
height= Height;
}
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is an object initialization?

A

To simplify objects initialization any accesible fields or properties can be set directly after constructor:
~~~
Bunny b1= new Bunny{ Name= “Bo”, LikesCarrots= true, LikesHumans= false};
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is a property?

A

A property is declared like a field but with a get/set block added
If you want to expose property as read-only to other types you can set a ‘set’ accesor to be private or protected or not set set accessor at all

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is a expression-bodied property?

A

You can write an expression with a fat arrow which replaces all the braces and return statements
~~~
public decimal Worth
{
get => currentPrice * sharesOwned;
set => sharesOwned = value / currentPrice;
}
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is a init-only setter?

A

Set accessor which lets you to set a property’s value when setting the property, but forbids you from modifying its value later on
~~~
{get; init;}
var note = new Note {Pitch= 50};
~~~
Then: note.Pitch = 200; // throws error

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is a finalizer?

A

Finalizers are class-only methods that executes before the garbage collector reclaims the memory of unreferenced object. The syntax is name of the class prefixes with ~ symbol
~~~
class Class1{
~Class1(){…}
}
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is a partial type?

A

Partial types allow a type definition to be split - typically across multiple files.
Each participant must have the ‘partial’ declaration

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Describe partial method

A

A partial method consist of two parts: a definition and an implementation.
Partial method must:
* be void and
* are implicitly private.
* They cannot include out parameters

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What are extended partial methods?

A

They are designed for the reverse code generation scenario
A partial method declaration is extended if it begins with an accessibility modifier:
~~~
public partial class Test{
public partial void M1();
}
~~~
Extended partial methods must have an implementation

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Why is the inheritance used?

A

A class can inherit from another class to extend or customise the original class. Inheriting from a class lets you reuse the functionality in that class instead of building it from scratch.
Class can inherit from only one class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is a polymorphism?

A

Polymorphism means that all subclasses (those which inherit) have all the features of the base class but not the other way around

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is an upcasting?

A

An upcast operation creates a base class reference from a subclass reference.
Although two objects refer to the identical object, upcasted one has a more restrictive view on that object:
~~~
House h = new House();
Object o = h;
~~~
Console. WriteLine(o.NumberOfWindows); // throws compile error

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is a downcasting operation?

A

A downcasting operation creates a subclass reference from a base class reference:
Stock stock= new Stock();
Asset a = stock; // Upcasting
Stock s = (Stock)a; // Downcasting

Only the references are affected to this change - not the underlying object. A downcast requires an explicit cast because it can potentially fail at runtime

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is a ‘as’ operator?

A

The ‘as’ operator performs a downcast that evaluates to null (rather than throwing an exception) if the downcasting fails
Asset a = new Asset();
Stock s = a as Stock; // s is null; No exception is thrown
In a case of exception the NullReferenceException is thrown rather than InvalidCastException in case of downcasting

25
Q

What is an ‘is’ operator?

A

The ‘is’ operator tests whether a variable matches a pattern - the is operator checks if an object derives from a specified class (or implements an interface):
if(a is Stock) Console.WriteLine(((Stock)a).SharesOwned)

26
Q

How can you check if the variable is of certain type and assert to that type’s variable in a simple way?

A

if(a is Stock s) is the same as :
~~~
Stock s;
if(a is Stock)
{
s = (Stock) a;
}
~~~

27
Q

How does virtual functions work?

A

A function marked as virtual can be overridden meaning if one class has a method marked virtual another class who inherits the first class has to implement that method which now has a ‘override’ modifier and a different functionality

28
Q

What is an abstract class?

A

A class declared as abstract can never be instantiated. Instead only its concrete subclasses can be instantiated.
Abstract classes are able to declare abstract members - they don’t provide a default implementations.
Virtual class members have a ‘virtual’ modifier, subclasses have ‘override’ modifier for the overridden methods (class dont have that)

29
Q

What is the difference between ‘new’ and ‘override’ modifiers in a subclasses if the subclasses derive from the same base class?
public override void Foo()….
public new void Foo()….

A

The difference will be seen if do the same upcasting method to those two classes the each method are in.
Lets say that the base class is called BaseClass
and have the same method Foo().
In the override case the called method b.Foo() will be calling the subclasses Foo() method o.Foo();
In the ‘new’ case the called method b.Foo() will be calling the BaseClass method Foo() instead of the subclasses method.

30
Q

What does the ‘sealed’ modifier do?

A

A ‘sealed’ modifier can prevent a class or a function member from being overridden by a subclass.
public sealed override int NumberOfCats => 1;

31
Q

What is a base keyword?

A

The base keyword is similar to ‘this’ keyword and serves two essential purposes:
- Accessing an overridden function member from the subclass
- Calling a base-class constructor:
~~~
public class House: Asset
{
public override decimal Liability => base.Liability + Mortgage;
}
~~~

32
Q

How can you describe relation of the BaseClass and SubClass constructors?

A

A subclass must declare its own constructors. The base class constructors are accessible but are never automatically inherited by the derived class.
Subclass must ‘redefine’ the base class constructor it wants to expose.
If the base class has a constructor Base(int x)….
the subclass can access it by SubClass(int x): base(x){}
Base class constructor in this scenario will always execute first.
If the subclasses constructor does not use the base keyword with their constructor, the base’s parametless constructor will still be called implicitly. If there is no parametless constructor the subclass will be forced to use ‘base’ keyword.

33
Q

What is the order in which the baseclass and subclass’s members are initialized?

A
  1. We start from subclasses fields
  2. Subclass constructor, but the “: base()” part
  3. Base class fields
  4. Base class constructor
  5. Subclass constructor
34
Q

What is a ‘stack’?

A

A stack is a data structure based on the principle LIFO - “Last In First Out”
A stack has two operations: ‘push’ an object on the stack and ‘pop’ an object off the stack

35
Q

What is ‘boxing’ and ‘unboxing’? Give an example for each

A

When you cast between a value type and ‘object’ (reference type) i.e. object -> int (putting int to the stack and taking it off), the CLR must perform some special work to bridge the difference in semantics between value and reference types.
Boxing - act of converting value-type instance to a reference-type instance.
Note: Reference type: object type, interface, System.ValueType, System.Enum
Example of boxing: int x = 9;
object o = x; // Box the int;
Example of unboxing:
int y = (int)obj; // unbox the int with explicit cast
The values are being copied both ways.

36
Q

When is the static type checking performed and when the Runtime type checking performed?

A

Static type checking is performed at compile-time to check the correctness of the program without running it.
Runtime type checking is performed whenever the downcasting is applied via unboxing or reference convertion. This type checking is performed by the CLR

37
Q

What is the difference between GetType() method and typeof operator?

A

They do the same thing, BUT GetType is evaluated at runtime and the typeof is evaluated statically at compile time
Point p = new Point();
p.GetType() == typeof(Point) // TRUE
p.GetType().Name == typeof (Point).Name // TRUE

38
Q

What is a struct?

A

A struct is similar to a class but:
- a struct is a value type, whereas a class is a reference type
- a struct does not support inheritance (other than implicitly deriving from object (System.Value))
Can have everything that a class has except of a finalizer. Also since it cannot be subclassed, members cannot be marked as virtual, abstract or protected.
Fields of a struct must be assigned (otherwise we get compile error)

39
Q

Give example when the struct would be used instead of a class

A

When creating many instances of a type it would require only a single heap allocation instead of instantiating every class instance on the heap

40
Q

What is a ref struct?

A

It is a struct that is ensured to always reside on the stack. Attempting to use a ref struct in such a way that it could reside on the heap generates a compile time error:
ref struct Point{…}
class MyClass {Point p}; // generates error because classes are of reference type and its members resides on the heap.
Also ref structs cannot appear inside non-ref structs and they cannot implement interfaces, because it can result in boxing

41
Q

Name and explain all access modifiers

A
  1. Public - fully accessible. This is the implicit accessibility for members of an enum or an interface
  2. Internal - accessible only within the containing assembly or friend assemblies
  3. Private - accessible only within containing type. This is the default accessibility for members of a class or struct
  4. Protected - accessible only within the containing type or subclasses
  5. Protected internal - the union of protected and internal therefore is accessible in two ways
  6. Private protected - a member that is private. Protected is accessible only within the containing type or subclasses that reside in the same assebly
42
Q

What is a friend assembly?

A

You can expose internal members to other friend assemblies by adding the System.Runtime.CompilerServices.InternalVisibleTo assembly attribute, specifying the name of a friend assembly

43
Q

What is an interface?

A

An interface is similar to a class but only specifies behaviour and does not hold state (data).
- An interface can define only functions and not fields (properyties can be);
- Interface members are implicitly abstract.
- A class or struct can implement multiple interfaces. In contrast a class can inherit from only a single class. Struct cannot inherit at all (besides deriving from System.ValueType)

44
Q

What does it mean to extend an interface?

A

For one interface to inherit from another.
In that case when a class implements this sub-interface it must implement all members from both interfaces.

45
Q

In which cases should we use explicit interface implementation?

A

When implementing multiple interfaces which members has conflicting signatures.
Another reason is to hide members that are highly specialized and distracting to a types normal use case.

46
Q

What are the problems of interface re-inmplemetation? How to avoid that?

A
  1. The subclass has no way to call the base class method
  2. The base class author might not anticipate that a method would be reimplemented and might not allow for the potential consequences
    Avoid by:
    a) When implicitly implementing a member, mark it as virtual if appropriate
    b) When explicitly implementing a member mark it as sealed if you dont anticipate any subclassing
47
Q

What are the advantages of defining a default method implementation to a interface?

A

This lets us to add a new method to a widely used interface without needing to implement it in various places (and breaking a code).
Default implementation is always called explicitly so in this way we avoid multiple implementation inheritance

48
Q

When should we use a class or an interface for inheritance?

A
  • Use classes and subclasses that naturally shares an implementation
  • Use interfaces for types that have independant impelemtations
49
Q

What is an enum?

A

An enum is a special value type that lets you specify a group of named numerics constants:
public enum BorderSide { Left, Right, Top, Bottom}
Usage: BorderSide.Top;
Each enum value has an underlying numeric value that is of int type starting from 0 (atuomatically assigned)

50
Q

How can you convert enum?

A

1: You can convert enum underlying value using explicit cast (int)BorderSide.Top
2: You can explicitly cast one enum to another Top = BorderSide.Bottom

51
Q

What are flag enums?

A

Flags attribute is usually aplicable to enums when members are combinble. Underlying values then assigned typically in powers of two: 0, 1, 2, 4, 8… to avoid :
~~~
[Flags]
public enum Sides { Left=0, Right=1, Top=2, Bottom=4);
~~~

52
Q

What is a nested type?

A

A nested type is declared within the scope of another type:
~~~
public class TopLevel{
public class Nested{}
public enum Color{ Red, Blue, Green}
}
~~~
Features:
- It can access the enclosing type’s private members and everything else the enclosing type can access
- You can declare it with the full range of access modifiers rather than just public and internal
- The default accessibility. for a nested type is private rather than internal
- Accessing a nested type from outside the enclosing type requires qualification with the enclosing type’s name (like when accessing a static members): TopLevelClass.Color.Red

53
Q

When a nested class should be used?

A

Nested type should be used because of its stronger access control restrictions or when the nested class must access private members of the containing class

54
Q

What is generics?

A

Generics is a way to write reusable code using ‘template’ that contains a ‘placeholder’ types <T>. Generics when compared to inheritance can increase type safety and reduce casting and boxing
Only methods and types can introduce type parameters, other can only use it.

55
Q

What are the generic constrains and what they are used for?

A

Constrains are applied to a type parameter to require more specific type arguments:
where T : base-class
Constraints can be used wherever the types are defined in both methods and type definitions

56
Q

What are the unmanaged constraint and naked type constraints?

A

Unmanaged constraint is a stronger version of a struct constraint: T must be a simple value type or a struct that is free of any reference types
Naked type constraint means that one type parameter require to derive from (or match) another type parameter.

57
Q

What is a covariance?

A

Its a conversions via an implicit reference conversion such as A subclassing B or A implementing B. Therefore we can do this
var bears = new List<Bears>(); // it implements Animals interface;
then this is possible:
List<Animals> animals = bears; // This is covariance

58
Q

What is contravariance?

A

in delegates is when delegates target method might return more specific type than described by the delegate;
Contravariance is when you can convert in reverse direction as suppose to covariance. The type parameter appears only in input position and is designated with ‘in’ modifier.:
public interface IPushable<in T> { void Push (T obj);}
We now can do this:
IPushable<Animal> animals = new Stack<Animal>();
IPushable<Bear> bears = animals; // !!!
bears.Push(new Bear());

59
Q

Name the differences between ‘int’, ‘nint’ and ‘uint’

A

In C#, there are three fundamental value types for representing integers: int, nint, and uint.

int: This is the most commonly used integer type in C#. It is a signed 32-bit integer, which means it can represent values ranging from -2,147,483,648 to 2,147,483,647. It is used to represent both positive and negative numbers.

nint: This is a new type introduced in C# 8.0 and is used to represent a signed native integer. Its size is platform-dependent, which means it will be 32 bits on 32-bit platforms and 64 bits on 64-bit platforms. It can represent values ranging from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. It is primarily used for interoperation with unmanaged code.

uint: This is an unsigned 32-bit integer that can represent values ranging from 0 to 4,294,967,295. Unlike int, it cannot represent negative numbers. It is used when only non-negative values are required, and the range of values needed exceeds that of int.

In summary, the main differences between these types are:

int and uint are both 32-bit types, while nint is platform-dependent.
int and nint are signed types, while uint is unsigned.
The range of values that can be represented by each type is different. int can represent values from -2,147,483,648 to 2,147,483,647, nint can represent values from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, and uint can represent values from 0 to 4,294,967,295.
nint is primarily used for interoperation with unmanaged code.