Often you learn new things when you re-learn basics. This post is fundamentals of C#. More than statements, for, while loops let’s look on basics of program execution, memory management, basics. Below listed are my notes from Illustrated C# 2010 Book.
Tip #1 - Why .NET is a strongly typed language ?
Type assignments are very strict. You cannot assign different types. Example - You cannot assign string to an integer in C#.
string a;int b;
b = 10;
a = b;
This would error (Compile time error). Identifying
type conversion error during compile time is advantage of strongly typed
language.
Tip #2 - What is Unified Type System ? - All types are derived from System.Object
- System.Object contains class, interface, delegate, string etc
- Value Types are derived from System.ValueType
- System.ValueType inherits from System.Object
- Stack is used for managing program execution; store certain variables, Store parameters sent for methods
- LIFO fashion (Data Deleted and Added from Top of Stack - Last In First Out)
- Value Types are Stored in Stack, Use less resource (Managed in Stack itself)
- Value Types Will not cause Garbage Collection as it is stored in Stack
- Example of Value Types - int, float, long, double, decimal, struct, enum
Tip #5 - What is Stored in Heap ? How it works ?
- Reference Types are stored in Heap. Garbage Collector manages heap memory
- Memory can be allocated and removed from any order (GC has its own algorithm to clear objects from Heap)
- Program can store data in Heap. GC removes data from Heap
- All Reference Type objects are stored in Heap (All the data members of the Object regardless of value type or reference type) they will be stored in Heap
- Ex- If you declare a class with data members, functions. The data members might belong to int, float data type. All the memory for them would be allocated in heap
- Example of Reference Types - Object, String, Classes, interface, delegate, array
Tip #6 -
What is output of below program ?
int
i = 20;
object j = i; //(Boxing)
j = 50; //(unboxing)
object j = i; //(Boxing)
j = 50; //(unboxing)
Value of i will still be 20. It is stored as a value type in stack with 20 as its value. J is stored as reference type in heap with value 50 assigned for J. In C with pointers concepts we can change the value of a variable with pointers
int a = 10;
int *b;
b = &a;
*b = 20;
Now the value of a will be set to 20
Tip #8 -
What is Boxing and Unboxing ?
Converting a value type to a reference type is
boxing. Boxing means creating a new instance of a reference type. Reference
types are always destroyed by garbage collection.
int
i = 20;
object j = i; //(Boxing)
object j = i; //(Boxing)
Converting a reference
type to value type is unboxing
int
i = 20;int k;
object j = i;
k = (int)j; //unboxing
Happy Learning!!!
No comments:
Post a Comment