CSHARP Quiz Questions with Answers

Table of Contents:

Csharp Quiz

1. Who created C#?

☐ Apple ☐ Google ☑ Microsoft ☐ Ecma

C# (/si: ʃɑːrp/) was developed around 2000 by Microsoft within its .NET initiative and later approved as a standard by Ecma (ECMA-334) and ISO (ISO/IEC 23270:2006).

C# is one of the programming languages designed for the CLI Common Language Infrastructure. Anders Hejlsberg has been the lead architect of the team developing the C# language since 2000.

2. What is CLR?

☐ Clear Left Right ☑ Common Language Runtime

Common Language Runtime is Microsoft’s implementation of the .NET runtime.

You can call it virtual machine that runs .NET programs (including those made in C#).

There is another popular CLR called Mono.

3. C# can run on Linux, Mac OS X, iOS, and Android?

True ☐ False

Although Microsoft invented C#, the language and its runtime are ECMA documented, enabling anyone to implement C#. This is not merely hypothetical.

The open source Mono project (sponsored by Microsoft) provides tools for building C# applications that run on Linux, Mac OS X, iOS, and Android.

4. Can you mix other .NET languages with C#?


Because the CLR supports multiple languages, you don’t have to pick just one for your whole project.

It’s common for primarily C#-based projects to use C++ to deal with a non-C#-friendly API, using the .NET extensions for C++.

Mixing languages works best when each language has a very clearly defined role in the project.

5. C# is?

statically typed language ☐ dynamically typed language

C# is a statically typed language. This means any element of code that represents or produces information, such as a variable or an expression has its data type determined at compile time.

There is another branch of dynamically typed languages, such as JavaScript, in which types are determined at runtime.

Note: C# does in fact offer dynamic typing as an option with dynamic keyword, but even then dynamic variables have a static type dynamic.

6. Following instructions:

conv.i, nop, ckfinite, throw, beq, ldarg.0 belong to:

☐ Java Bytecode instruction set ☐ x86 instruction set ☑ CIL instruction set ☐ something other

The Common Intermediate Language (CIL) instruction set is true. These are the human readable instructions that are defined by the Common Language Infrastructure (CLI).

Java bytecode instructions use _(underscore) character. x86 instructions are single worded without dots.

7. To work with C# compiler (csc.exe) it is best to have:

Developer Command Prompt for VS ☐ PowerShell ☐ MSBuild ☐ Command Prompt

The Developer Command Prompt for VS (or Visual Studio Command Prompt) automatically sets the environment variables that enable you to easily use .NET Framework tools from the command line.

PowerShell and regular Command Prompt won’t run csc.exe out of the box.

Visual Studio uses MSBuild to load and build managed projects. The project files in Visual Studio (.csproj, .vbproj, .vcxproj, and others) contain MSBuild XML files.

8. For the code:

int willNotWork;

willNotWork is:


Compiler will complain: error CS0165: Use of unassigned local variable 'willNotWork'

meaning willNotWork is an unassigned variable.

C# compiler will always panic, forcing you to assign variables. This is OK:

int willNotWork=0;

9. What is variable scope?

☐ either public or protected or internal or private ☑ the region of code in which you can refer to that variable by its name

Public, protected, internal or private are called access modifiers.

In C# anything with the name has scope. A scope is a region in which you can refer to the entity by its name without needing additional qualification.

When you write Math.PI you refer to the constant PI, but you need to qualify it with a class name Math, because simple PI may be undefined.

When I write Console.WriteLine I am referring to the method by its name WriteLine, but I need to qualify it with a class name Console, because the method is not in scope.

10. You can build the executable in Visual Studio if your solution doesn’t have any project in it?

☐ YES ☑ NO

You can’t build anything in Visual Studio if the solution does not have any project.

11. To switch between Debug and Release build you need to tweak the settings on:

☐ project level ☑ solution level

Configuration settings, such as choice between Debug and Release builds, are controlled at the solution level.

12. Visual Studio installer can:

☐ install, modify, repair, and uninstall Visual Studio ☐ update workloads and individual components ☐ update language in Visual Studio ☑ all true

Visual Studio installer is a great tool that can help you tweak Visual Studio.

13. Which version is free for commercial use?

☐ Visual Studio Enterprise edition ☐ Visual Studio Professional edition ☑ Visual Studio Community edition ☐ No Visual Studio edition is free or commercial use

A startup or small business can use Visual Studio Community Edition to develop commercial applications.

14. How can you output CIL instructions from a managed executable to a standard output?

ildasm man.exe /output:man.ilildasm man.exe /text

You can use Developer Command Prompt and execute ildasm man.exe /text to output the instructions to the standard output.

You can use Developer Command Prompt and execute ildasm man.exe /output:man.il to store the list of instructions to a file.

15. C# compiler produces:

☐ machine code ☑ managed code

C# compiler will produce managed code. Some compilers produce only the machine code.

Some compilers like Microsoft C++ compiler can produce both managed and unmanaged code. Note: Managed means managed by .NET language runtime.

16. The file that MSBuild tool understands as a solution in Visual Studio has the extension


.sln is a textual file that represents the solution.

.prj extension is not used.

.csproj is an XML file that represents the project.

.suo is a binary file that contains per-user settings, record of which files you have open, and which project or projects to launch when starting debug sessions. That ensures that when you open a project, everything is more or less where you left it when you last worked on the project.

17. Will this work?

int something;
something = "something";

☐ YES ☑ NO

Because variables have a static type, the compiler will reject attempts to assign the wrong kind of data.

Note: This would be allowed in dynamic languages such as JavaScript, because a JavaScript variable doesn’t have its own type.

18. Will this work?

var something;
something = "something";


C# has the var keyword meaning variable of any type. This way the compiler will select the appropriate type for you.

Note: You will not be able to write something like:

var something = "something";
something = 1;

because the variable something will be statically typed as System.String. The compiler will yield:

CS0029 C# Cannot implicitly convert type 'int' to 'string'

19. C# long takes

64 bits ☐ 32 bits ☐ 16 bits ☐ 128 bits

C# long takes 64 bits or 8 Bytes.

You can check the size like this: Console.WriteLine(sizeof(long)); It will return 8.

20. What type will take the biggest size?

☐ int ☐ float ☑double ☐ byte

double is the biggest size.


Will result:


21. What is correct?

ulong u1 = 123ul;ulong u2 = 123UL;ulong u3 = 123Lu;All correct

There will be no problems in any case.

ulong u1 = 123ul;
ulong u2 = 123UL;
ulong u3 = 123Lu;

Compiler will not complain.

22. C# property:

☐ can have both setter and getter ☐ can have just setter ☐ can have just getter ☑ all true

Properties in a class typically expose class members via getter and setter special functions.

public class HasProperty
   private int _x;
   public int X
     get { return _x; }
     set { _x = value; }

CIL compiler will create two methods get_X and set_X behind this code. You may define just the setter or just the getter.

23. What would be wrong to use as operator with the operator keyword?

☐+ ☐ true ☐ int ☑ new

Using +, -, >, <, <=, … as operators is common practice if you define your custom types.

public static X operator +(X x, int y)
   return new X(x.Count + y);

The main scenario for the true and false operators is to enable custom types to use && and || Boolean operators.

You can define conversion operators like this:

public static operator int(X value)
   return value.Count;

But you cannot use the keyword new as operator. Also you cannot define custom meanings for the . operator.

24. We can add a field to an interface?

☐ YES ☑ NO

Interfaces cannot contain fields or nested types.

Interfaces only define the API, not the implementation.

25. Will the next code fail?

public interface IDoStuff
   string this[int i] { get; set; }
   string Name { get; set; }
   int Id { get; }
   int SomeMethod(string arg);
   event EventHandler Click;

☐ YES ☑ NO

The code

public interface IDoStuff
   string this[int i] { get; set; }
   string Name { get; set; }
   int Id { get; }
   int SomeMethod(string arg);
   event EventHandler Click;

will work because all we define here will convert to methods.

There is no field definition here and there will be no compilation error.

26. Can we define a constructor inside the interface?

☐ YES ☑ NO

Interfaces cannot declare constructors.

Think interfaces are like object services. An object may supply one, once it has been constructed.

Note: Most interfaces in .NET follow the convention that their name starts with an uppercase I.

27. Anonymous type have a name?

☐ YES ☑ NO

C# an anonymous type, as the name suggests, is without a name.

C# allows you to create an object with the new keyword without defining its class. The implicitly typed variable var is used to hold the reference of anonymous types.

var x = new { Name = ""Rust"", Born = 2010 };
Console.WriteLine(""Welcome, "" + x.Name + "" "" + x.Born);

28. Will this code work?

var x = new { };


This code will work:

var x = new { };

This would be defining the anonymous type taking 0 parameters. Internally the csc.exe (C# compiler) will create the <>f__AnonymousType1 name for this type.

Note: In C# variable names cannot start with <> but the compiler uses the above name not to collide with any possible name.

29. What is not part of method signature in C# defined by ECMA-334 (C# standard)?

☐ method name ☐ order of method parameters ☑ return type ☐ parameter types

Return type is not part of the method signature in C#.

Only the method name and its parameters types are part of the signature.

Parameter names are also irrelevant.

30. What method will work with this delegate?

public delegate int PerformCalculation(int x, int y);

static int X(int x, int y);public int PerformCalculation();public long PerformCalculation(int x, int y);public var PerformCalculation(int x, int y);

A delegate is a type that represents references to methods.

Delegates must match the method return type and also parameter(s) order and type.

When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.

Delegates are used to pass methods as arguments to other methods. Event handlers are nothing more than methods that are invoked through delegates.

31. What is not true for a delegate in C#?

☐ They can refer to static methods or instance methods. ☐ They can refer to more than one method. ☑ You create them only with Delegate.CreateDelegate() method ☐ You create them with new keyword

Delegate.CreateDelegate() static method is just one option to create a delegate.

You can also use the new keyword or you can create them on stack without the new keyword.

A delegate object is normally constructed by providing the name of the method the delegate will wrap, or with an anonymous Method.

delegate void myDelegate();

32. Anonymous function and anonymous method are the same thing in C#?

☐ True ☑ False

The C# specification defines the term anonymous function as an alternative name for an inline method with a non-void return type, while an anonymous method is an inline method defined with the delegate keyword.

33. In C# there are reference types and value types. Which one is the reference type?


Variables of reference type store reference to their data. Variables of value type directly contain their data.

With reference types (class, interface, delegate, dynamic, object, string) two variables can reference the same object and operations on one variable can affect the object referenced by the other variable.

With value types (bool, byte, char, decimal, double, enum, float, int, long, sbyte, short, struct, uint, ulong, ushort) each variable has its own copy of the data except in the case of in, ref and out parameter variables.

Note: All array types are implicitly derived from System.Array, which itself is derived from System.Object. This means that all arrays are always reference types.

34. What is Encapsulation?

☐ Wrapping functions into a single unit ☐ Wrapping functions and data into a single unit ☐ Making the whole data accessible to the outer world ☑ Hiding some data and some functions not needed to the outer world

Encapsulation, in the context of C#, refers to an object’s ability to hide data and behavior that are not necessary to the outer world.

Encapsulation enables a group of properties, methods and other members to be considered as a single unit or object.

35. What is true for the events?

☐ use event keyword to declare them ☐ you can subscribe to event using += operator ☐ you can unsubscribe from event using -= operator ☑ All true

After checking inside IL adding and removing events will transform to add_ and remove_ methods.

You declare the event like this:

public event EventHandler eh;

and then at some point call:

observable.eh += observer.HandleEvent;

Operator += will transform to something like Observable::add_eh

The event keyword is the best way to work with events as it provides the level of encapsulation that the delegate keyword cannot provide.

36. In C#, you should use which keyword to protect your code from exceptions?


try − A try block identifies a block of code for which a particular exception is activated. It is followed by one or more catch blocks.

catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.

finally − The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.

throw − A program throws an exception when a problem shows up. This is done using a throw keyword.

37. Will this code compile without errors?

abstract class Shape
  public abstract void Draw();
class Rectangle : Shape
  public override void Draw();

☐ True ☑ False

This is the example of the abstract class Shape and the derived class Rectangle.

Here is the error that will occur:

Error CS0501 'Rectangle.Draw()' must declare a body because it is not marked abstract, extern, or partial

With minimum improvement we can get this working:

abstract class Shape
  public abstract void Draw();
class Rectangle : Shape
  public override void Draw(){ }

Note: In here the Draw(){} is the empty method.

38. What can we tell for the object x

class X
   public override void draw();
class Y
   public static void Main()
     X x;

☐ it is assigned ☑ it is unassigned

To assign the object x we need to use the new keyword.

class X
  public override void draw();
class Y
  public static void Main()
    X x = new X();

This is a very frequent mistake especially for C++ developers. Thankfully, the compiler will panic.

39. Can we have a method inside a namespace?

☐ YES ☑ NO

No. Defining the method will produce this error: Error CS0116 A namespace cannot directly contain members such as fields or methods

You cannot define members or methods inside a namespace.

40. Given the following code, what is happening in the second line?

int i = 5;
object o = i;
int j = (int) o;

boxing ☐ unboxing

You have two variables: i is a value type variable. o is a reference type variable. How does it make sense to assign the value of i to o.

int i = 5;
object o = i;
int j = (int) o;

The value of o should be the reference, not the integer value. Behind this example we have so called boxing. Runtime will create an object on the heap with the value 5 that is a copy of the original value.

Next if we change the value of i this will not change the value on heap.

Unboxing (third line) extracts the value from the box to the int j variable.

41. Following naming conventions in C# is a must?

☐ YES ☑ NO

Following naming conventions is great but not obligatory.

Convention usually depends on project bases. Still it is pretty common to use convention like this in C#:

MyClass (class)
MyMethod (method)
myLocalVariable (local variable)
_myLocalVariable (private variable)
MyProperty (property)
MyConstant (constant)

42. What is a bitwise complement operator?


~ is a bitwise complement operator.

! is logical NOT

^ binary XOR

& is binary AND operator

43. Which of the following statements can be used for declaring a two dimensional array?

int arr[][];int arr[,];int[][] arr;int[ , ] arr;

This is the example of 2x2 two dimensional array:

int[ , ] arr = new int[ , ]
   {1, 2},
   {3, 4},
// ... Print out values.
Console.WriteLine(arr[0, 0]);
Console.WriteLine(arr[0, 1]);
Console.WriteLine(arr[1, 0]);
Console.WriteLine(arr[1, 1]);

int[] [] arr; this would be the array of arrays.

44. What is the output of the following code?

class C
  public static void Main()
    string str = @"x:\\y\\z";

x:\\y\\zx:\y\z"x:\\y\\z" ☐ compiler error

The correct output is x:\\y\\z.

When we use string str = @"x:\\y\\z"; compiler will generate the string "x:\\\\y\\\\z" for us.

@ is called a verbatim string literal.

@ can be also used for multiline strings like this:

string query = @"SELECT foo, bar
FROM table
WHERE name = 'a\b'";

The only bit of escaping is that if you want a double quote, you have to add an extra double quote symbol if you need double single double quote.

Console.WriteLine(@"" """" ""); // will output ""

45. What is [Serializable] in here?

public class C {  
  public int i1 = 0;    
  public String s = null;  

An attribute tag ☐ Property

[Serializable] is an attribute.

An attribute is a declarative tag that is used to convey information at runtime about the behaviors of various elements like classes, methods, structures, enumerators, assemblies etc.

A tag is depicted by square [ ] brackets placed above the element it is used for.

This attribute tells that objects will later be saved to a binary file for instance:

C o = new C();  
o.n1 = 1;  
o.s = ""foo"";  
IFormatter f = new BinaryFormatter();  
Stream s = new FileStream(""a.bin"", FileMode.Create, FileAccess.Write, FileShare.None);  
f.Serialize(s, o);  

46. One of these operators you cannot overload. Which one?


These operators can be overloaded:

+, -, !, ~, ++, --, true, false, *, /, %, &, ☐, ^, <<, >>, ==, !=, <, >, <=, >=

These operators cannot be overloaded:

&&, || , [] , (T) x, +=, -=, *=, /=, %=, &=, ☐=, ^=, <<=, >>=, =, ., ::, ?:, ??, ->, =>, f(x), as, checked, unchecked, default, delegate, is, new, sizeof, typeof

47. Which namespace is not defined in .NET?


Not defined is System.Thread.

There is one similar called System.Threading.

48. Lambda expressions are used only in LINQ?

☐ True ☑ False

Lambda expressions are absolutely crucial to LINQ.

They’re not restricted to working with LINQ. Any use of anonymous methods can use lambda expressions in C#, and that will almost always lead to shorter code.

49. Asynchronous functions can have multiple await expressions inside?

True ☐ False

C# 5 introduces the concept of an asynchronous function declared with the async modifier, that can include multiple await expressions inside.

There should be at least one await expression inside.

If you mark your method async but don’t use await anywhere, then your method won’t be asynchronous.

50. Is there a difference between arr1 and arr2?

int[] arr1 = new int[] {1, 2, 3}
int[] arr2 = {1, 2, 3}

☐ Yes, these are different ☑ No, these are exactly the same

Here it is completely irrelevant which one is used.

int[] arr1 = new int[] {1, 2, 3}
int[] arr2 = {1, 2, 3}

ildasm will show the exact code for both the cases.

tags: quiz - answers - csharp - csharp programmers - c# - quiz questions - quiz answers - c# quiz - C# quiz questions - C# answers - quiz questions in c# - beginners - intermediate - .NET framework - c# class - C# class property & category: csharp