C# Interview Questions and Answers

C#.NET Interview Questions And Answers

In this article, I am going to discuss the most frequently asked 50 C# Interview Questions and Answers. This is part 1 of the C# .NET Interview Questions and Answers article series and hence in this article, we are going to discuss frequently asked basic C# Interview Questions and Answers and in our upcoming articles, we will discuss the experienced Interview questions. As part of this article, we are going to discuss the following C# Interview Questions with Answers.

  1. What is COM and what are the disadvantages of COM?
  2. What .NET Represents?
  3. What is a Framework and what does the .NET Framework provide?
  4. Explain about CLR and its Execution Process.
  5. What is exactly .NET?
  6. What are the language and its need?
  7. What are Technology and its need?
  8. What is Visual Studio?
  9. Explain about BCL.
  10. What is the Just-In-Time (JIT) compilation?
  11. What are Metadata and an assembly?
  12. What are the differences between managed code and unmanaged code?
  13. What is C#?
  14. What is the difference between an EXE and a DLL?
  15. What’s the difference between IEnumerable<T> and List<T>?
  16. Why is class an abstract data type?
  17. What are the new features introduced in C# 7?
  18. Why should you override the ToString() method?
  19. What is the difference between string keyword and System.String class?
  20. Are string objects mutable or immutable in C#?
  21. What do you mean by String objects are immutable?
  22. What is a verbatim string literal and why do we use it?
  23. How do you create empty strings in C#?
  24. What is the difference between System.Text.StringBuilder and System.String?
  25. How do you determine whether a String represents a numeric value?
  26. What is the difference between int.Parse and int.TryParse methods?
  27. What are Properties in C#? Explain with an example?
  28. What are the different types of properties available in C#?
  29. What are the advantages of using properties in C#?
  30. What is a static property? Give an example?
  31. What is Virtual Property in C#? Give an example?
  32. What is an Abstract Property in C#? Give an example?
  33. Can you use virtual, override, or abstract keywords on an accessor of a static property? 
  34. What are the 2 broad classifications of data types available in C#?
  35. How do you create user-defined data types in C#?
  36. Difference between int and Int32 in C#
  37. What are the differences between value types and reference types?
  38. What do you mean by casting a data type?
  39. What are the 2 kinds of data type conversions available in C#?
  40. What is the difference between an implicit conversion and an explicit conversion?
  41. What is the difference between int.Parse and int.TryParse methods?
  42. What is Boxing and Unboxing in C#?
  43. What happens during the process of boxing?
  44. What are Access Modifiers in C#?
  45. Can we use all access modifiers for all types?
  46. Can derived classes have greater accessibility than their base types?
  47. Can the accessibility of a type member be greater than the accessibility of its containing type?
  48. Can destructors have access modifiers?
  49. What does protected internal access modifiers mean?
  50. Can you specify an access modifier for an enumeration? 
What is COM?
  1. COM stands for Component Object Model.
  2. COM is one of Microsoft Technology. Using this technology we can develop windows applications as well as web applications.

In earlier COM, VB is the programming language that is used to implement windows applications and ASP is used to implement web applications.

What are the disadvantages of COM?

The major two disadvantages of COM is

  1. Incomplete object-oriented programming means it will not support all the features of OOPs.
  2. Platform dependent means COM applications can run on only Windows OS.
What .NET Represents?
  1. NET stands for Network Enabled Technology.
  2. In .NET dot (.) refers to object-oriented and NET refers to the internet.

So the complete .NET means through object-oriented we can implement internet applications.

What is a Framework?

A framework is software. Or we can say that a framework is a collection of many small technologies integrated together to develop applications that can be executed anywhere.

What does the .NET Framework provide?

.NET Framework provides two things such as

  1. BCL (Base Class Libraries)
  2. CLR (Common Language Runtime)
Explain about BCL.
  1. Base Class Libraries are designed by Microsoft.
  2. Without BCL we can’t write any code in .NET so BCL also was known as the Building block of Programs of .NET.
  3. These are installed into the machine when we installed the .NET framework into the machine.

The physical location of BCL is C:\Windows\assembly

BCL contains predefined classes and these classes are used for the purpose of application development.

Explain about CLR and its Execution process.

CLR is the core component under the .NET framework which is responsible for converting MSIL code into native code and then execution.

C#.NET Interview Questions and Answers

In .NET, the code is compiled twice.

  1. In 1st compilation source code is compiled by the respective language compiler and intermediate code is generated known as MSIL (Microsoft Intermediate Language) or IL (Intermediate language code) Or Managed code.
  2. In the 2nd compilation, MSIL is converted into Native code using CLR.

Always 1st compilation is slow and 2nd compilation is first.

What is JIT?
  1. JIT stands for Just-in-time.
  2. JIT is the component of CLR that is responsible for converting MSIL code into Native code.
  3. This Native code is directly understandable by the operating system.
Explain different types of .NET Framework.

The .Net framework is available in three different types

  1. .NET Framework: This is the general version required to run .NET applications on Windows OS only.
  2. .NET mono Framework: This is required if we want to run .NET applications on other OS like Unix, Linux, MAC OS, etc.
  3. .NET Compact Framework: This is required to run .NET applications on other devices like mobile phones and smartphones.

Note: MSIL is only CPU dependent and will run only on Windows OS only using .NET Framework because .NET Framework is designed for Windows OS only.

There is another company known as “NOVEL” that designed a separate framework known as “MONO Framework”. Using this framework we can run MSIL on different OS Like Linux, UNIX, Mac, BSD, OSX, etc. .NET is platform-dependent using the .NET framework but independent using the MONO framework.

What is not .NET?
  1. .NET is not an Operating system.
  2. It is not an application or package.
  3. .NET is not a database.
  4. It is not an ERP application.
  5. .NET is not a Testing Tool.
  6. It is not a programming language.
What is exactly .NET?

.NET is a framework tool that supports many programming languages and many technologies. It supports 60+ programming languages. In 60+ programming languages, 9 are designed by Microsoft and the remaining are designed by Non-Microsoft.

Microsoft designed programming languages are as follows

  1. VB.NET
  2. C#.NET
  3. VC++.NET
  4. J#.NET
  5. F#.NET
  6. Jscript.NET
  7. WindowsPowerShell
  8. Iron Phyton
  9. Iron Ruby

Technologies supported by the .NET framework are as follows

  1. ASP.NET (Active Server Pages.NET)
  2. ADO.NET (Active Data Object.NET)
  3. WCF (Windows Communication Foundation)
  4. WPF (Windows Presentation Foundation)
  5. WWF (Windows Workflow Foundation)
  6. AJAX (Asynchronous JavaScript and XML)
  7. LINQ (Language Integrated Query)
  8. ASP.NET MVC (Model View Controller)
  9. ASP.NET WEB API
What are the language and its need?
  1. A language acts as the mediator between the programmer and the system.
  2. It offers some rules and regulations for writing the program.
  3. The language also offers some libraries which are required for writing the program.
  4. The collection of programs is called software.
What are Technology and its needs?

Technology is designed for a particular purpose. For example development of web-related applications in .NET using a technology ASP.NET. But the technology does not offer any specific rules for writing the programs. That’s why technology can’t be implemented individually.

VB.NET, C#.NET both are programming languages. Using these two languages we can implement windows/desktop applications individually. Every language is having its own compiler

Basic C# Interview Questions and Answers

VB.NET, C#.NET:

VB.NET and C#.NET both are programming languages. Using these two programming languages we can develop windows applications.

ASP.NET:
  1. ASP.NET is a part of a Framework.
  2. ASP.NET is a technology that provides a set of predefined classes. Using these classes we can implement web applications.
  3. ASP.NET is needed language support.
ADO.NET:
  1. ADO stands for ActiveX Data Objects.
  2. The ADO.NET is a .NET database technology.
  3. ADO.NET provides a set of predefined classes. Using these predefined classes we can perform the operations with the database server.
WCF:
  1. WCF stands for Windows Communication Foundation.
  2. The WCF is a distributed technology. Using this technology we can implement SOA (Service Oriented Architecture) programming.
  3. SOA programming provides communication between heterogeneous applications.
  4. Applications that are developed using different technologies or different programming languages are known as heterogeneous applications.
WPF:
  1. The WPF stands for windows presentation foundation.
  2. WPF is a .NET technology using this technology we can create 2D, 3D, graphics, animations for windows application.
  3. Using this technology we can also create our own audio/video players and also implement gaming applications.
LINQ:
  1. LINQ stands for Language Integrated Query.
  2. It is query-writing Technology.
  3. LINQ offers to write queries in the programming code itself.
  4. This concept is introduced in .NET framework 3.5
  5. LINQ queries applying in database data and non-database data also.
What is Visual Studio?

Visual Studio is a Microsoft IDE tool that is needed to develop applications with the .NET framework. The IDE integrates 3 features

  1. Editor
  2. Compiler
  3. Interpreter
What is .Net?
  1. .NET is a programming framework created by Microsoft that developers can use to create applications more easily. The framework provides libraries commonly used by developers. The .NET Base Class Libraries (BCL) servers that purpose.
  2. The .NET provides language interoperability across several programming languages. Programs are written for .NET Framework execute in a software environment called Common Language Runtime (CLR).
  3. CLR is the foundation of the .NET framework which provides services like safety, memory management, garbage collection, and exception handling.
  4. CLR manages the execution of code. The code that is managed by CLR is called managed code. Unmanaged code does not get managed by CLR. CLR’s interoperability helps to interact between managed and unmanaged code.
  5. Common Language Specification (CLS) and Common Type System (CTS) as part of CLR. CTS is responsible for interpreting data types into a common format. CLS provides the ability of code to interact with code that is written with a different programming language.
What is the Just-In-Time (JIT) compilation?

The MSIL is the language that all of the .NET languages compile down to. After they are in this intermediate language, a process called Just-In-Time compilation occurs when resources are used from our application at runtime.

What is metadata?

Metadata describes every type and member defined in our code in a Multilanguage form. Metadata stores the following information.

  1. Description of assembly.
  2. Identity (name, version, culture, public key).
  3. The types that are exported
  4. Other assemblies that this assembly depends on.
  5. Security permissions needed to run.
What is an assembly?

Assemblies are the building block of .NET framework applications; they form the fundamental unit of deployment, version control, reuse, and activation scoping and security permissions.

What are the differences between managed code and unmanaged code?

This is one of the frequently asked C# Interview Questions and Answers. Let us discuss the difference between them.

Managed code/methods:
  1. Machine instructions are in MSIL format and located in assemblies will be executed by the CLR will have the following advantages
  2. Memory management to prevent memory leaks in program code.
  3. Thread execution
  4. Code safety verification
  5. Compilation.
Unmanaged code/ methods:
  1. The Unmanaged codes are the instructions that are targeted for specific platforms. Unmanaged code will exist in any of the formats. 
  2. COM/COM+ components
  3. Win 32 Dlls/system DLLs
  4. As these codes are in native formats of OS, these instructions will be executed faster compared with JIT compilation and execution of managed code.
What is C#?

C# is an object-oriented typesafe and managed language that is compiled by the .Net framework to generate Microsoft Intermediate Language.

What is the difference between an EXE and a DLL?

This is one of the frequently asked C# Interview Questions and Answers. Let us understand the difference between Exe and DLL. EXE is an executable file and can run by itself as an application whereas DLL is usually consumed by an EXE or by another DLL and we cannot run or execute DLL directly.

For example in .NET compiling a Console Application or a Windows Application generates EXE, whereas compiling a Class Library Project or an ASP.NET web application generates DLL. In the .NET framework, both EXE and DLL are called assemblies.

A DLL can be reused in the application whereas an exe file can never be reused in an application. EXE stands for executable, and DLL stands for Dynamic Link Library

What’s the difference between IEnumerable<T> and List<T>?
  1. IEnumerable is an interface, whereas List is one specific implementation of IEnumerable. A list is a class.
  2. FOR-EACH loop is the only possible way to iterate through a collection of IEnumerable whereas List can be iterated using several ways. The list can also be indexed by an int index, the element can be added to and removed from and have items inserted at a particular index.
  3. IEnumerable doesn’t allow random access, whereas List does allow random access using the integral index.
  4. In general from a performance standpoint, iterating through IEnumerable is much faster than iterating thru a List
Why is class an abstract data type?

A Class is an Abstract Data Type because it specifies what data members and member functions (methods) contain in it (class), but won’t provide information on how those are implemented. That makes Class Abstract and Class is User Defined DataType. So, it’s an Abstract Data Type

What are the new features introduced in C# 7?

This is a very commonly asked C# interview question. This question is basically asked to check if you are passionate about catching up with the latest technological advancements. The list below shows the new features that are introduced in C# 7. Let’s have a look at the new features that are introduced as part of C# 7

  1. Out variables
  2. Pattern matching
  3. Digit Separators
  4. Tuples
  5. Deconstruction (Splitting Tuples)
  6. Local functions
  7. Literal improvements
  8. Ref returns and locals
  9. Generalized async return types
  10. More expression-bodied members
  11. Throw expressions
  12. Discards
  13. Async main
  14. Default literal expressions
  15. Inferred tuple element names
Why should you override the ToString() method? 

This C# Interview Question is one of the most frequently asked .NET questions. All types in .Net inherit from the System.Object directly or indirectly. Because of this inheritance, every type in .Net inherits the ToString() method from System.Object class. Consider the example below.

C# Interview Questions and Answers

In the above example Number.ToString() method will correctly give the string representation of int 10, when we call the ToString() method. If we have a Customer class as shown in the below example and when we call the ToString() method the output does not make any sense. Hence we have to override the ToString() method, which is inherited from the System.Object class.

public class Customer
{
    public string FirstName;
    public string LastName;
}
public class MainClass
{
    public static void Main()
    {
        Customer C = new Customer();
        C.FirstName = "David";
        C.LastName = "Boon";
        Console.WriteLine(C.ToString());
    }
}

The code sample below shows how to override the ToString() method in a class, that would give the output you want.

public class Customer
{
    public string FirstName;
    public string LastName;

    public override string ToString()
    {
        return LastName + ", " + FirstName;
    }
}
public class MainClass
{
    public static void Main()
    {
        Customer C = new Customer();
        C.FirstName = "David";
        C.LastName = "Boon";
        Console.WriteLine(C.ToString());
    }
}

Conclusion: If we have a class or a struct, make sure you override the inherited ToString() method.

What is the difference between string keyword and System.String class? 

string keyword is an alias for System.String class. Therefore System.String and string keywords are the same, and we can use whichever naming convention we prefer. The String class provides many methods for safely creating, manipulating, and comparing strings.

Are string objects mutable or immutable? 

String objects are immutable.

What do you mean by String objects are immutable?

This C# Interview Question is frequently asked .NET Interviews. String objects are immutable means they cannot be changed after they have been created. All of the String methods and C# operators that appear to modify a string actually return the results in a new string object. In the following example, when the contents of s1 and s2 are concatenated to form a single string, the two original strings are unmodified. The += operator creates a new string that contains the combined contents. That new object is assigned to the variable s1, and the original object that was assigned to s1 is released for garbage collection because no other variable holds a reference to it.

string s1 = "First String ";
string s2 = "Second String";

// Concatenate s1 and s2. This actually creates a new
// string object and stores it in s1, releasing the
// reference to the original object.

s1 += s2;
System.Console.WriteLine(s1);

// Output: First String Second String
What will be the output of the following code? 
string str1 = "Hello ";
string str2 = str1;
str1 = str1 + "C#";
System.Console.WriteLine(str2);

The output of the above code is “Hello” and not “Hello C#”. This is because, if you create a reference to a string, and then “modify” the original string, the reference will continue to point to the original object instead of the new object that was created when the string was modified.

What is a verbatim string literal and why do we use it? 

The “@” symbol is the verbatim string literal. Use verbatim strings for convenience and better readability when the string text contains backslash characters, for example in file paths. Because verbatim strings preserve newline characters as part of the string text, they can be used to initialize multiline strings. Use double quotation marks to embed a quotation mark inside a verbatim string. The following example shows some common uses for verbatim strings:

string ImagePath = @"C:\Images\Buttons\SaveButton.jpg";
//Output: C:\Images\Buttons\SaveButton.jpg

string MultiLineText = @"This is multiline
Text written to be in
three lines.";
/* Output:
This is multiline
Text written to be in
three lines.
*/

string DoubleQuotesString = @"My Name is ""Pranaya.""";
//Output: My Name is "Pranaya."
Will the following code compile and run? 

string str = null;
Console.WriteLine(str.Length);

The above code will compile but at runtime System.NullReferenceException will be thrown.

How do you create empty strings in C#? 

Using string.empty as shown in the example below.

string EmptyString = string.empty;

What is the difference between System.Text.StringBuilder and System.String?

This is one of the frequently asked C#.NET Interview Questions. Objects of type StringBuilder are mutable whereas objects of type System.String is immutable. As StringBuilder objects are mutable, they offer better performance than string objects of type System.String. The StringBuilder class is present in System.Text namespace where String class is present in System namespace.

How do you determine whether a String represents a numeric value?

To determine whether a String represents a numeric value using the TryParse method as shown in the example below. If the string contains non-numeric characters or the numeric value is too large or too small for the particular type you have specified, TryParse returns false and sets the out parameter to zero. Otherwise, it returns true and sets the out parameter to the numeric value of the string.

string str = "One";
int i = 0;

if(int.TryParse(str,out i))
{
     Console.WriteLine("Yes string contains Integer and it is " + i);
}
else
{
     Console.WriteLine("string does not contain Integer");
}
What is the difference between int.Parse and int.TryParse methods?

The parse method throws an exception if the string you are trying to parse is not a valid number whereas TryParse returns false and does not throw an exception if parsing fails. Hence TryParse is more efficient than Parse.

What are Properties in C#? Explain with an example?

It is one of the frequently asked C# Interview Questions. Properties in C# are class members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.

In the example below _firstName and _lastName are private string variables that are accessible only inside the Customer class. _firstName and _lastName are exposed using FirstName and LastName public properties respectively. The get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels. The value keyword is used to define the value being assigned by the set accessor. The FullName property computes the full name of the customer. The FullName property is read-only because it has only the get accessor. Properties that do not implement a set accessor are read-only.

The code block for the get accessor is executed when the property is read and the code block for the set accessor is executed when the property is assigned a new value.

class Customer
{
    // Private fileds not accessible outside the class.
    private string _firstName = string.Empty;
    private string _lastName = string.Empty;
    private string _coutry = string.Empty;

    // public FirstName property exposes _firstName variable
    public string FirstName
    {
        get
        {
            return _firstName;
        }
        set
        {
            _firstName = value;
        }
    }
    // public LastName property exposes _lastName variable
    public string LastName
    {
        get
        {
            return _lastName;
        }
        set
        {
            _lastName = value;
        }
    }
    // FullName property is readonly and computes customer full name.
    public string FullName
    {
        get
        {
            return _lastName + ", " + _firstName;
        }
    }
    //Country Property is Write Only
    public string Country
    {
        set
        {
            _coutry = value;
        }
    }

}
class MainClass
{
    public static void Main()
    {
        Customer CustomerObject = new Customer();
        //This line will call the set accessor of FirstName Property
        CustomerObject.FirstName = "David";
        //This line will call the set accessor of LastName Property
        CustomerObject.LastName = "Boon";
        //This line will call the get accessor of FullName Property
        Console.WriteLine("Customer Full Name is : " + CustomerObject.FullName);
    }
}
What are the different types of properties available in C#? 

In C#, there are three types of Properties available. They are shown in the following image.

  1. Read-Only Properties: Properties without a set accessor are considered read-only. In our example, FullName is a read-only property.
  2. Write Only Properties: Properties without a get accessor are considered write-only. In our example, the Country is a write-only property.
  3. Read Write Properties: Properties with both a get and set accessor are considered read-write properties. In our example, FirstName and LastName are read-write properties.
What are the advantages of using properties in C#?
  1. Properties can validate data before allowing a change.
  2. It can transparently expose data on a class where that data is actually retrieved from some other source such as a database.
  3. Properties can take action when data is changed, such as raising an event or changing the value of other fields.
What is a static property? Give an example? 

A property that is marked with a static keyword is considered as a static property. This makes the property available to callers at any time, even if no instance of the class exists. In the example below PI is a static property.

Properties Interview Questions and Answers in C#

What is Virtual Property in C#? Give an example? 

This is one of the most frequently asked C#.NET Interview Questions. A property that is marked with a virtual keyword is considered virtual property. Virtual properties enable derived classes to override the property behavior by using the override keyword. In the example below FullName is a virtual property in the Customer class. BankCustomer class inherits from Customer class and overrides the FullName virtual property. In the output, you can see the overridden implementation. A property overriding a virtual property can also be sealed, specifying that for derived classes it is no longer virtual.

class Customer
{
    private string _firstName = string.Empty;
    private string _lastName = string.Empty;

    public string FirstName
    {
        get
        {
            return _firstName;
        }
        set
        {
            _firstName = value;
        }
    }
    public string LastName
    {
        get
        {
            return _lastName;
        }
        set
        {
            _lastName = value;
        }
    }
    // FullName is virtual
    public virtual string FullName
    {
        get
        {
            return _lastName + ", " + _firstName;
        }
    }
}
class BankCustomer : Customer
{
    // Overriding the FullName virtual property derived from customer class
    public override string FullName
    {
        get
        {
            return "Mr. " + FirstName + " " + LastName;
        }
    }
}
class MainClass
{
    public static void Main()
    {
        BankCustomer BankCustomerObject = new BankCustomer();
        BankCustomerObject.FirstName = "David";
        BankCustomerObject.LastName = "Boon";
        Console.WriteLine("Customer Full Name is : " + BankCustomerObject.FullName);
    }
}
What is an Abstract Property in C#? Give an example?

A property that is marked with the abstract keyword is considered abstract property. An abstract property should not have any implementation in the class. The derived classes must write their own implementation. In the example below FullName property is abstract in the Customer class. BankCustomer class overrides the inherited abstract FullName property with its own implementation.

using System;
abstract class Customer
{
    private string _firstName = string.Empty;
    private string _lastName = string.Empty;

    public string FirstName
    {
        get
        {
            return _firstName;
        }
        set
        {
            _firstName = value;
        }
    }
    public string LastName
    {
        get
        {
            return _lastName;
        }
        set
        {
            _lastName = value;
        }
    }
    // FullName is abstract
    public abstract string FullName
    {
        get;
    }
}
class BankCustomer : Customer
{
    // Overriding the FullName abstract property derived from customer class
    public override string FullName
    {
        get
        {
            return "Mr. " + FirstName + " " + LastName;
        }
    }
}
class MainClass
{
    public static void Main()
    {
        BankCustomer BankCustomerObject = new BankCustomer();
        BankCustomerObject.FirstName = "David";
        BankCustomerObject.LastName = "Boon";
        Console.WriteLine("Customer Full Name is : " + BankCustomerObject.FullName);
    }
}
Can you use virtual, override, or abstract keywords on an accessor of a static property? 

No, it is a compile-time error to use a virtual, abstract, or override keywords on an accessor of a static property.

Is C# a strongly-typed language? 

Yes

What are the 2 broad classifications of data types available in C#?
  1. Built-in data types.
  2. User-defined data types.
Give some examples of built-in data types in C#?
  1. Int
  2. Float
  3. Bool
How do you create user-defined data types in C#? 

You use the struct, class, interface, and enum constructs to create your own custom types. The .NET Framework class library itself is a collection of custom types provided by Microsoft that you can use in your own applications. 

Difference between int and Int32 in C#

This is one of the frequently asked C# Interview Questions and Answers. Int32 and int are synonymous, both of them allow us to create a 32-bit integer. int is shorthand notation (alias) for Int32. When declaring an integer in a c# program most of us prefer using int over Int32. Whether we use int or Int32 to create an integer, the behavior is identical. 

Data Types Interview Questions and Answers in C#

I think the only place where Int32 is not allowed is when creating an enum. The following code will raise a compiler error stating – Type byte, sbyte, short, ushort, int, uint, long, or ulong expected.

enum Test : Int32
{
    abc = 1
}

The following code will compile just fine
enum Test: int
{
    abc = 1
}

I can think of only the following minor differences between int and Int32

  1. One of the differences is in readability. When we use Int32, we are being explicit about the size of the variable.
  2. To use Int32, either we need to use using System declaration or specify the fully qualified name (System.Int32) whereas with int it is not required.
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 value type or reference type? 

Value Type

If you define a user-defined data type by using the class keyword, Is it 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 of value types?
  1. Enum
  2. Struct
Give examples for reference types? 
  1. Class
  2. Delegate
  3. Array
  4. Interface
What are the differences between value types and reference types?

This is one of the frequently asked C# Interview Questions and Answers. Value types are stored on the stack whereas reference types are stored on the managed heap. The Value type variables directly contain their values whereas reference variables hold only a reference to the location of the object that is created on the managed heap.

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 overhead of object allocation and garbage collection.

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.

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

Structs can inherit from System.ValueType class but cannot be inherited by any other types like Structs or Class. In other words, Structs are like Sealed classes that cannot be inherited.

What do you mean by casting a data type? 

Converting a variable of one data type to another data type is called casting. This is also called data type conversion.

What are the 2 kinds of data type conversions available in C#?

Implicit conversions: No special syntax is required because the conversion is typesafe and no data will be lost. Examples include conversions from smaller to larger integral types and conversions from derived classes to base classes.

Explicit conversions: Explicit conversions require a cast operator. The source and destination variables are compatible, but there is a risk of data loss because the type of the destination variable is a smaller size than (or is a base class of) the source variable.

What is the difference between an implicit conversion and an explicit conversion? 

Explicit conversions require a cast operator whereas an implicit conversion is done automatically. The Explicit conversion can lead to data loss whereas with implicit conversions there is no data loss.

What type of data type conversion happens when the compiler encounters the following code?

ChildClass CC = new ChildClass();
ParentClass PC = new ParentClass();

Implicit Conversion: For reference types, an implicit conversion always exists from a class to any one of its direct or indirect base classes or interfaces. No special syntax is necessary because a derived class always contains all the members of a base class.

Will the following code compile? 

double d = 9999.11;
int i = d;

No, the above code will not compile. Double is a larger data type than the integer. An implicit conversion is not done automatically because there is a data loss. Hence we have to use explicit conversion as shown below.

double d = 9999.11;
int i = (int)d; //Cast double to int.

If you want to convert a base type to a derived type, what type of conversion do you use?

Explicit conversion as follows. Create a new derived type.
Car C1 = new Car();

Implicit conversion to the base type is safe.
Vehicle V = C1;

Explicit conversion is required to cast back to the derived type. The code below will compile but throw an exception at runtime if the right-side object is not a Car object.
Car C2 = (Car) V;

What operators can be used to cast from one reference type to another without the risk of throwing an exception? 

The is and as operators can be used to cast from one reference type to another without the risk of throwing an exception.

If casting fails what type of exception is thrown?

InvalidCastException

What is the difference between int.Parse and int.TryParse methods?

This is one of the frequently asked C# Interview Questions and Answers. The parse method throws an exception if the string you are trying to parse is not a valid number whereas TryParse returns false and does not throw an exception if parsing fails. Hence TryParse is more efficient than Parse.

What are Boxing and Unboxing? 

Boxing – Converting a value type to reference type is called boxing. An example is shown below.
int i = 101;
object obj = (object)i; // Boxing

Unboxing – Converting a reference type to a value type is called unboxing. An example is shown below.

obj = 101;
i = (int)obj; // Unboxing

Is boxing an implicit conversion?

Yes, boxing happens implicitly.

Is unboxing an implicit conversion? 

No, unboxing is an explicit conversion.

What happens during the process of boxing?

This is one of the frequently asked C# Interview Questions and Answers. Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. Boxing a value type allocates an object instance on the heap and copies the value into the new object. Due to this boxing and unboxing can have a performance impact.

What are Access Modifiers in C#? 

This is one of the frequently asked C# Interview Questions and Answers. In C# there are 5 different types of Access Modifiers.

  1. Public: The public type or member can be accessed by any other code in the same assembly or another assembly that references it.
  2. Private: The type or member can only be accessed by code in the same class or struct.
  3. Protected: The type or member can only be accessed by code in the same class or struct, or in a derived class.
  4. Internal: The type or member can be accessed by any code in the same assembly, but not from another assembly.
  5. Protected Internal: The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly.
What are Access Modifiers used for?

Access Modifiers are used to control the accessibility of types and members within the types.

Can we use all access modifiers for all types? 

No, not all access modifiers can be used by all types of members in all contexts, and in some cases, the accessibility of a type member is constrained by the accessibility of its containing type.

Can derived classes have greater accessibility than their base types?

No, Derived classes cannot have greater accessibility than their base types. For example, the following code is illegal.

Access Modifiers Interview Questions in C# with Answers

When we compile the above code an error will be generated stating “Inconsistent accessibility: base class InternalBaseClass is less accessible than class PublicDerivedClass“. To make this simple, you cannot have a public class B that derives from an internal class A. If this were allowed, it would have the effect of making public, because all protected or internal members of A are accessible from the derived class.

Is the following code legal in C#?
private class Test
{
    public static void Main()
    {
    }
}

No, a compile-time error will be generated stating Namespace elements cannot be explicitly declared as private, protected, or protected internal

Can you declare struct members as protected? 

No, struct members cannot be declared protected. This is because structs do not support inheritance.

Can the accessibility of a type member be greater than the accessibility of its containing type?

No, the accessibility of a type member can never be greater than the accessibility of its containing type. For example, a public method declared in an internal class has only internal accessibility.

Can destructors have access modifiers? 

No, destructors cannot have access modifiers.

What does protected internal access modifiers mean?

The protected internal access means protected OR internal, not protected, AND internal. In simple terms, a protected internal member is accessible from any class in the same assembly, including derived classes. To limit access to only derived classes in the same assembly, declare the class itself internal, and declare its members as protected.

What is the default access modifier for a class, struct, and an interface declared directly with a namespace? 

internal

Will the following code compile in C#?
interface IInterface
{
    public void Save();
}

No, you cannot specify the access modifier for an interface member. Interface members are always public.

Can you specify an access modifier for an enumeration? 

Enumeration members are always public, and no access modifiers can be specified.

In the next article, I am going to discuss Interface and Inheritance related interview questions and answers in C#. Here, in this article, I try to explain the most frequently asked Basic C# Interview Questions and Answers. I hope you enjoy this Basic C#.NET Interview Questions and Answers article. 

1 thought on “C# Interview Questions and Answers”

Leave a Reply

Your email address will not be published. Required fields are marked *