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.

8 comments:

  1. If structs cannot inherit then how can they be derived from System.ValueType?

    ReplyDelete
  2. i guess that System.ValueType is an interface :)

    ReplyDelete
  3. I guess you are wrong because System.ValueType is derived from System.Object and it can't be an interface

    ReplyDelete
  4. No System.ValueType is a class..(Daniyal)

    ReplyDelete
  5. My 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)

    ReplyDelete
  6. My understanding is that just because structs inherit from System.ValueType, they cannot inherit from another class, because we cannot do multiple class inheritance. (Anthony)

    ReplyDelete
  7. Structs 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

If you are aware of any other C# questions asked in an interview, please post them below. If you find anything missing or wrong, please feel free to correct by submitting the form below.

 
Disclaimer - Terms of use - Contact Us