C# Interview Questions on value types and reference types
What are the 2 types of data types available in C#?
1. Value Types
2. Reference Types
If you define a user defined data type by using the struct keyword, Is it a a value type or reference type?
Value Type
If you define a user defined data type by using the class keyword, Is it a a value type or reference type?
Reference type
Are Value types sealed?
Yes, Value types are sealed.
What is the base class from which all value types are derived?
System.ValueType
Give examples for value types?
Enum
Struct
Give examples for reference types?
Class
Delegate
Array
Interface
What are the differences between value types and reference types?
1. Value types are stored on the stack where as reference types are stored on the managed heap.
2. Value type variables directly contain their values where as reference variables holds only a reference to the location of the object that is created on the managed heap.
3. There is no heap allocation or garbage collection overhead for value-type variables. As reference types are stored on the managed heap, they have the over head of object allocation and garbage collection.
4. Value Types cannot inherit from another class or struct. Value types can only inherit from interfaces. Reference types can inherit from another class or interface.
Subscribe to:
Post Comments (Atom)
If structs cannot inherit then how can they be derived from System.ValueType?
ReplyDeletei guess that System.ValueType is an interface :)
ReplyDeleteIt is an Abstract class.
DeleteI guess you are wrong because System.ValueType is derived from System.Object and it can't be an interface
ReplyDeleteNo System.ValueType is a class..(Daniyal)
ReplyDeleteMy understanding is that just because structs are inherited from System.ValueType, they cannot inherit from another class, because we cannot do multiple class inheritance. (Anthony)
ReplyDeleteMy understanding is that just because structs inherit from System.ValueType, they cannot inherit from another class, because we cannot do multiple class inheritance. (Anthony)
ReplyDeleteStructs can Inherit from System.ValueType class but can not be inherited by any other types like Structs or Class. In other words Structs are like Sealed Class that can not be inherited.
ReplyDelete