Structures/Generics Flashcards

1
Q

Value-Types vs Reference-Types

A

Value Types (Structures, Enumerations)

  • Mainly meant for storing simple values.
  • Instances (examples) are called as “structure instances” or “enumeration instances”.
  • Instances are stored in “Stack”. Every time when a method is called, a new stack will be created.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Reference Types (string, Classes, Interfaces, Delegates)

A
  • Mainly meant for storing complex / large amount of values.*Instances (examples) are called as “Objects” (Class Instances / Interface Instances / Delegate Instances).
  • Instances (examples) are called as “Objects” (Class Instances / Interface Instances / Delegate Instances).

* Instances (objects) are stored in “heap”. Heap is only one for entire application.

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

Structures

A

Structure is a “type”, similar to “class”, which can contain fields, methods, parameterized constructors, properties and events.

The instance of structure is called as “structure instance” or “structure variable”; but not called as ‘object’. We can’t create object for structure. Objects can be created only based on ‘class’.

Structure instances are stored in ‘stack’.

Structure doesn’t support ‘user-defined parameter-less constructor and also destructor.

Structure can’t inherit from other classes or structures.

Structure can implement one or more interfaces.

Structure doesn’t support virtual and abstract methods.

Structures are mainly meant for storing small amount of data (one or very few values).

Structures are faster than classes, as its instances are stored in ‘stack’.

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

Class (vs) Structure- structures properties

A

Structures

Structures “value-types”.

Structure instances (includes fields) are stored in stack. Structures doesn’t require Heap.Structure instances (includes fields) are stored in stack. Structures doesn’t require Heap.

Suitable to store small data (only one or two values).

Memory allocation and de-allocation is faster, in case of one or two values.

Structures doesn’t support Parameter-less Constructor.

Structures doesn’t support inheritance (can’t be parent or child).

The “new” keyword just initializes all fields of the “structure instance”.

Structures doesn’t support abstract methods and virtual methods.

Structures doesn’t support destructors.

Structures are internally derived from “System.ValueType”. System.Object -> System.ValueType -> Structures

Structures doesn’t support to initialize “non-static fields“, in declaration.

Structures doesn’t support “protected” and “protected internal” access modifiers.

Structure instances doesn’t support to assign “null”.

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

Class (vs) Structure- class

A

Classes
____________________________________________________

Classes are “reference-types”.

Class instances (objects) are stored in Heap; Class reference variables are stored in stack.

Suitable to store large data (any no. of values)

Memory allocation and de-allocation is a bit slower.

Classes support Parameter-less Constructor.

Classes support Inheritance.

The “new” keyword creates a new object.

Classes support abstract methods and virtual methods.

Classes support destructors.Classes are internally and directly derived from “System.Object”. System.Object -> Classes

Classes supports to initialize “non-static fields“, in declaration.

Classes support “protected” and “protected internal” access modifiers.

Class’s reference variables support to assign “null”.

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

Constructors in Structures

A

C# provides a parameter-less constructor for every structure by default, which initializes all fields.

You can also create one or more user-defined parameterized constructors in structure.

Each parameterized constructor must initialize all fields; otherwise it will be compile-time error.

The “new” keyword used with structure, doesn’t create any object / allocate any memory in heap; It is a just a syntax to call constructor of structure.

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

Read-only Structures

A

Use readonly structures in case of all of these below:

All fields are readonly.

All properties have only ‘get’ accessors (readonly properties).

There is a parameterized constructor that initializes all the fields.

You don’t want to allow to change any field or property of the structure.

Methods can read fields; but can’t modify.

‘Readonly structures’ is a new feature in C# 8.0.

This feature improves the performance of structures.

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

Primitive Types as Structures

A

All primitive types are structures.

For example, “sbyte” is a primitive type, which is equivalent to “System.SByte” (can also be written as ‘SByte’) structure.

In C#, it is recommended to always use primitive types, instead of structure names.

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

System.Object class

A

The “System.Object” is a pre-defined class, which is the “Ultimate super class (base class)” in .net.

All the classes and other types are inherited from System.Object directly / indirectly.

All C# classes, structures, interfaces, enumerations are children of System.Object class.

Every method defined in the Object class is available in all objects in the system as all classes in the .NET Framework are derived from Object class.

Derived classes can override Equals, GetHashCode and ToString methods of Object class.

System.Object class is meant for achieving “type safety” in C#.

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

Methods of System.Object class

A

System.Object Class [Pre-defined]

namespace System
{
class Object
{
virtual bool Equals( object value );
virtual int GetHashCode( );
Type GetType( );
virtual string ToString( );
}
}

› bool Equals( object value )

Compares the current object with the given argument object; returns true, if both are same objects; returns false, if both are different objects.

› int GetHashCode( object value )

Returns the a number that represents the object. It is not guarantee that the hash code is unique, by default.

› Type GetType( )

Returns the name of the class (including namespace path), based on which, the object is created.

› string ToString( )

By default, it returns the name of the class (including namespace path), based on which, the object is created.

It is virtual method, which can be overridden in the child class.

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

Boxing

A

It is a process of converting a value from “Value-Type Data Type” to “Reference-Type Data Type”, if they are compatible data types.

This can be done automatically [no need of any syntax].

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

Unboxing

A

It is a process of converting a value from “Reference-Type Data Type” to “Value-Type Data Type”, if they are compatible data types.

This should be done explicitly (by using explicit casting).

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

Generics

A

Generic class is a class, which contains one or more “type parameters”.

You must pass any data type (standard data type / structure / class), while creating object for the generic class.Object of Generic Class - Example

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

Object of Generic Class - Example

A

ClassName<int> referenceVariable = new ClassName<int> ( );</int></int>

The same field may belong to different data types, w.r.t. different objects of the same class.

You will decide the data type of the field, while creating the object, rather than while creating field in the class.

It helps you in code reuse, performance and type-safety.

You can create your own generic-classes, generic-methods, generic-interfaces and generic-delegates.

You can create generic collection classes. The .NET framework class library contains many new generic collection classes in System.Collections.Generic namespace.

The generic type parameter (T) acts as “temporary data type”, which represents the actual data type, provided by the user, while creating object.

You can have multiple “generic type parameters” in the same class (for use for different fields.

Generics are introduced in C# 2.0.

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

Generic Constraints

A

Generic Constraints are used to specify the types allowed to be accepted in the “generic type parameter”.

where T : class

where T : struct

where T : ClassName

where T : InterfaceName

where T : new( )

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

Understanding Generic Constraints

A

Advantage: You can restrict what type of data types (class names) allowed to be passed while creating object.

In C#, constraints are used to restrict a generics to accept only particular type or its derived types.

By using ‘where’ keyword, we can apply constraints on generics.

You can apply multiple constraints on generic classes or methods based on your requirements.

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

Generic Methods

A

Generic Method is a method that has one or more generic parameter(s).

You can restrict what type of data types to be allowed to be passed to the parameter while calling the method.

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

Nullable Types

A

Value Types (structures, enumerations)

-Value Types are by default non-nullable types.
-Non-nullable types doesn’t support ‘null’ values to be assigned to its variables.

Reference Types (classes, interfaces)
-Reference Types are by default nullable types.
-Nullable types support ‘null’ values assigned to its variables.
-They don’t require the following syntax.

19
Q

What is null?

A

Represents ‘blank’ value.

Eg: In Employee class, the ‘int CreditCardNumber’ can be ‘null’.

20
Q

Null coalescing operator

A

The ‘null coalescing operator’ checks whether the value is null or not.

It returns the left-hand-side operand if the value is not null.

It returns the right-hand-side operand if the value is null.

Advantage: Simplifying the syntax of ‘if statement’ to check if the value is null.

Syntax:

variableName ?? valueIfNull

21
Q

Null Propagation Operator

A

The “Null Propagation Operator ( ?. ) and ( ? [] ) checks the value of left-hand operand whether it is null or not.

It returns the right-hand-side operand (property or method), if the value is not null.

It returns null, if the value is null.

It accesses the property or method, only if the reference variable is “not null”; just returns “null”, if the reference variable is “null”.

Null Propagation Operator ( ?. ) - Syntax

referenceVariable?.fieldName;

– is same as –

(referenceVariable == null)? null : referenceVariable.fieldName;

Advantage: We can invoke desired member (property or method) after checking if null.

22
Q

Extension Methods

A

Extension method is a method injected (added) into an existing class (or struct or interface), without modifying the source code of that class (or struct or interface).

23
Q

Extension Methods properties

A

The developer of ClassLibrary, creates a class with a set of methods. The consumer of ClassLibrary, can add additional methods to the same class, without modifying the source code of the ClassLibrary.

You can add additional methods to pre-defined classes / structures such as String, Int32, Console etc.

You must create a static class with a static method; that it will be added as a non-static method to the specified class.

This feature is introduced in C# 3.0.

The first parameter of extension must be having “this” keyword; followed by the class name / structure name, to which you want to add the extension method. Eg: this ClassName parameter

The parameter (with ‘this’ keyword) represents the current object, just like “this” keyword in the instance methods.

Extension method can have any no. of additional parameters, where the “this” keyword parameter is must.

Extension method does not support method overriding. That means, extension method’s signature can’t be same as any existing method.

You can also add extension methods to sealed class.

‘Extension Methods’ concept can’t be used to create fields, properties, or events.

The static class of extension method can’t be inner class.

The namespace in which the static class of extension method is created, must be imported in order to call the extension method as non-static method.

24
Q

Pattern Matching

A

It allows you to declare a variable, while checking the data type (class) of a reference variable, and automatically type-casts the reference variable into the specified data type (class).

Advantage: Simplified syntax to perform multiple checks of data types and type-casts.

25
Q

Implicitly-Typed Variables

A

The variables that are declared with ‘var’ keyword are called as ‘implicitly-typed variables’ (a.k.a type-inference).

VAR VARIABLES

Implicitly-typed variables are declared without specifying the ‘type’ explicitly; so that the C# compiler automatically identifies the appropriate data type at compilation-time, based on the value assigned at the time of declaration.

While declaration, the ‘type’ of implicitly-typed variables is fixed. It is not possible to change the type of that variable or assign “other type of values” into the implicitly typed variables, after declaration.

Implicitly Typed Variables can only be “local variables”; can’t be used for method parameters, return type or fields.

Implicitly Typed Variables must be initialized along with declaration.

It is not possible to declare multiple implicitly typed variables in the same statement. Eg: var x = 10, y = 20; //error

It is not possible to assign “null” into implicitly typed variables (while declaration). Eg: var x = null; //error

26
Q

Dynamically-Typed Variables

A

Dynamically Typed Variables are the variables that are declared with ‘dynamic’ keyword.

Declared without specifying the type explicitly.

There is no fixed type for the variable.

You can assign any type of value to these variables.

C# compiler skips “type-checking” at compilation time; instead, it resolves the data types of its values, at run time.

The “dynamic” type variables are converted as “object” type in most cases. Eg: dynamic dynamicVariable = 100; -> object dynamicaVariable = 100;

The Dynamically Typed Variable can change its data type, any no. of times, at run time.

Methods and other members of ‘dynamically typed variables’ will not be checked by the compiler at compilation time; will be checked by CLR at run time.

If the method or other member not available, it would not cause compile-time error; it raises run-time error, when the execution flow encountered that particular statement. Eg: dynamicVariable.NonExistingMethod( ); //run-time error (exception)

The Dynamically Typed Variables need not be initialized, while declaration.

The Dynamically Typed Variable doesn’t have “Intellisense” in Visual Studio.

The “dynamic” keyword is allowed for local variables, method parameters, fields, properties, return types etc.

27
Q

Inner Classes

A

“Inner Class” (a.k.a. Nested Class) is a class, which is created in another class (outer-class or containing-class).

Advantage: We can create all inter-related classes of a class, “inner classes”.

Syntax to access inner classes: OuterClassName.InnerClassName

By default, inner class is “private”; so it is accessible within the same outer class. To make it available to outside of the outer class, you can use other access modifiers such as “protected”, “private protected”, “internal”, “protected internal” or “public”.

A nested class can be declared as a private (default), public, protected, internal, protected internal, or private protected.

Outer class can’t access the members of inner class directly, without object.

Inner class can’t access the members of outer class directly, without object.

You are allowed to create objects of inner class in outer class; and vice versa; but you can’t do both; if you create objects vice-versa, it causes StackOverflowException.

You can create a child class for the inner class, outside the outer class.

28
Q

Garbage Collection

A

Garbage Collection is a process of deleting objects from memory, to free-up memory; so the same memory can be re-used.

29
Q

How Garbage Collection Works?

A

CLR automatically allocates memory for all objects created any where in the application, whenever it encounters “new ClassName( )” statement. This process is called as “Memory Management”, which is done by “Memory Manager” component of CLR.

All objects are stored in “Heap” (a.k.a. virtual memory).

Heap is only-one for the entire application life time.

The default heap size 64 MB (approx.), and extendable.

When CLR can’t find space for storing new objects, it performs a process called “Garbage Collection” automatically, which includes “identification of un-referenced objects and deleting them from heap; so that making room for new objects”. This process is done by “Garbage Collector (GC)” component of CLR.

30
Q

How GC decides if objects are alive?

A

› GC checks belongs information from the MSIL code:

› It collects references of an object.

› The objects that are referenced by at least one reference variable (or reference field) are “alive objects”; others are “dead objects” or “un-used objects”.

31
Q

When GC gets triggered?

A

There are NO specific timings for GC to get triggered.

GC automatically gets trigged in the following conditions:

  • When the “heap” is full or free space is too low.
  • When we call GC.Collect() explicitly.
32
Q

Generations in GC

A

Heap contains three segments (called generations):

Generation 2 [Long-Lived Generation]

Generation 1 [Survival Generation]

Generation 0 [Short-Lived Generation]

33
Q

Generation 0 GC

A

The “Generation 0” is the youngest generation and contains newly created short-lived objects and collected at first priority. The objects survive longer, are promoted to “Generation 1”.

Eg: The newly created objects.

34
Q

Generation 1 GC

A

The “Generation 1” is buffer between “Generation 0” and “Generation 2”.

The “Generation 1” mainly contains frequently-used and longer-lived objects.

Eg: The objects created in the previously-executed methods, but still accessible.

35
Q

Generation 2 GC

A

The “Generation 2” contains the longest-lived objects that were created long-back and still is being used, by different statements in the program.

Eg: The objects that referenced with static fields.

36
Q

Managed (vs) Unmanaged Resources

A

Managed Resources

The objects that are created by CLR are called as “Managed Resources”.

These will participate in “Garbage Collection” process, which is a part of .NET Framework.

Unmanaged Resources

The objects that are not created by CLR and not managed by CLR are called as “Un-managed resources”.

Eg: File streams, database connections

37
Q

Clearing Unmanaged Resources

A

Destructor

Clears unmanaged resources just before deleting the object; i.e. generally at the end of application execution.

Dispose

Clears unmanaged resources after the specific task (work) is completed; so no need to wait till end of application execution.

38
Q

Destructor

A

Destructor is a special method of the class, which is used to close un-managed resources (such as database connections and file connections), that are opened during the class execution.

Syntax:

~ClassName( )
{
//body here…
}

We close database connections and file connections; so no memory wastage or leakage.

Destructor doesn’t de-allocate any memory; it just will be called by CLR (.net runtime engine) automatically, just before a moment of deleting the object of the class.

39
Q

Rules of Destructor

A

Destructor’s name should be same as class name, started with ~ (tilde) character.

A Destructor is unique to its class i.e. there cannot be more than one destructor in a class.

Destructor can’t have parameters or return value.

Destructor is “public” by default, we can’t change its access modifier.

Destructor doesn’t support any other modifiers such as “virtual”, “abstract”, “override” etc.

Destructors can be defined only in classes; but not in structs, interfaces etc.

Destructors can’t be overloaded or inherited.

Destructors are usually called at the end of program execution.

40
Q

Destructor (vs) Finalize method

A

Internally, destructor is compiled as the “Finalize” method.

The “destructor” is a term belongs to C# language; the “Finalize” method belongs to .net framework generally; and both are same (interchangeable).

The compiled Finalize method calls the Finalize method of corresponding base class.

41
Q

IDisposable and Dispose

A

The “IDisposable” interface of “System” namespace, has a method called “Dispose”, which is used to close un-managed resources that are created during the life-time of the object.

The un-managed resources include file streams and database connections.

At the end of “using” statement, automatically “Dispose” method will be called.

Dispose is better than Destructor, because we need wait till ‘end of application execution’ to clear unmanaged resources; we clear them immediately after usage.

42
Q

Using Declaration

A

You can prefix “using” keyword before the local variable declaration, in order to call “Dispose” method when that variable goes out of scope.

43
Q
A