Structures/Generics Flashcards
Value-Types vs Reference-Types
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.
Reference Types (string, Classes, Interfaces, Delegates)
- 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.
Structures
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’.
Class (vs) Structure- structures properties
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”.
Class (vs) Structure- class
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”.
Constructors in Structures
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.
Read-only Structures
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.
Primitive Types as Structures
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.
System.Object class
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#.
Methods of System.Object class
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.
Boxing
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].
Unboxing
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).
Generics
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
Object of Generic Class - Example
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.
Generic Constraints
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( )
Understanding Generic Constraints
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.
Generic Methods
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.
Nullable Types
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.
What is null?
Represents ‘blank’ value.
Eg: In Employee class, the ‘int CreditCardNumber’ can be ‘null’.
Null coalescing operator
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
Null Propagation Operator
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.
Extension Methods
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).
Extension Methods properties
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.
Pattern Matching
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.