You are on page 1of 17

Essentials of C# Programming FAQ

(Frequently Asked Questions)

© Aptech Ltd Version 1.0 Page 1 of 17


Essentials of C# Programming FAQ

Table of Contents
S# Question
1. What happens when we instantiate a struct without the new keyword?
2. Do delegates really provide type safety?
3. How is the == operator different from object.Equals()?
4. Why should we provide a property for a private field and write set and get
accessors when it is easier to simply declare the field as public?
5. What is the use of the /target: command line option?
6. How can we create a constant that is an array?
7. What version of .NET should be used to use generics?
8. How can an array be resized?
9. How is const different from static readonly?
10. How can a destructor be made virtual?
11. Can two arrays be concatenated?
12. Why should the Main() method be declared as static?
13. Is it possible to declare the override method as static when the original
method is non-static?
14. Can enums, structs, or sealed classes be used as generic constraints?
15. How is a struct different from a class?
16. Does C# consist of an in-built class library?
17. Can the get and set accessors of a property have different access
modifiers?
18. In an inheritance hierarchy, the destructors of which class are called first?
19. What happens if I catch an exception but do not write any code inside the
catch block to handle the exception?
20. Why are data members of the Hashtable class stored using the private
access modifier?
21. How is the System.Array.CopyTo() method different from the
System.Array.Clone() method?
22. If varOne.Equals(varTwo) returns true, does it imply that
varOne.GetHashcode will return the same hash code as
varTwo.GetHashcode?
23. Is it possible for the compiler to execute multiple catch blocks for a single
try block?
© Aptech Ltd Version 1.0 Page 2 of 17
Essentials of C# Programming FAQ

24. How is the ref modifier different from the out modifier?
25. What is the difference between managed and unmanaged code?
26. What is an assembly?
27. Can the scope of a field or method of a class to the classes in the same
namespace be restricted?
28. How can we create a DLL in C#?
29. If the Console.WriteLine() method encounters a NULL character within a
string, will it stop printing the output?
30. What is the GAC? Why is it used?
31. Can an async method have multiple await operators?
32. Where can we configure the endpoint address of a WCF service?
33. In cryptography, what is hashing?
34. What factors should we consider before selecting either symmetric or
asymmetric encryption to encrypt data?

35. Which .NET Framework version comes with Visual Studio 2017?

36. Is Visual Studio available for free?


37. How is FCL different from CTS?
38. Does Visual Studio 2017 support open source languages?
39. Why is C# preferred over C++?
40. How is a local function better than lambda expression?
41. What is deconstruction in C#?
42. What is the function of digital separator in C#?
43. How is pattern matching done using switch?
44. What are the key features of C# 7.0 and 7.1?
45. Are all the features of C# 7.1 made available by default to the users?
46. What is the enhancement with respect to tuples in C#7.1?
47. Where to use .NET Core?
48. What is a docker?
49. What is dependency injection?
50. How does .NET enable working in visual form?
51. What is the advantage of extension method?
52. What is LINQ to Entities?
53. What is the role of an identifier in a namespace?

© Aptech Ltd Version 1.0 Page 3 of 17


Essentials of C# Programming FAQ

54. What are the new tools in Debugger environment in Visual Studio 2017?
55. How to set a breakpoint in the debugger tool?
56. What is the use of a Data Tip?
57. How can a package be reused by developers?

© Aptech Ltd Version 1.0 Page 4 of 17


Essentials of C# Programming FAQ

What happens when we instantiate a struct without the new keyword?


When the new keyword is used to instantiate a structure, it is the constructor that
initializes the fields declared in the structure. However, when the new keyword is not
used, the fields of the structure have to be explicitly initialized.

Do delegates really provide type safety?


No, delegates do not really provide type safety. The instance of a delegate only
ensures that the encapsulated methods are compatible with the delegate’s type, it
is not concerned with the classes of the delegates.

How is the == operator different from object.Equals()?


While working with value types, the == operator and Equals() method perform the
same function, namely comparing the two objects by value. On the other hand,
while working with reference types, the == operator performs an identity
comparison and returns true, if both references refer to the same object. However,
the Equals() method can perform a value comparison, if the method has been
appropriately overridden in the class inheriting the System.Object class.

Why should we provide a property for a private field and write set
and get accessors when it is easier to simply declare the field as
public?
Properties are not only used to provide access to fields of the class, but also used to
provide controlled access. Properties provide security to data and ensure that no
invalid values are assigned to the fields of the class.

© Aptech Ltd Version 1.0 Page 5 of 17


Essentials of C# Programming FAQ

What is the use of the /target: command line option?


The /target: command line options are exe, library, module, and winexe. The exe,
library, and winexe options are used to create .NET assemblies. Based on the
provided option, the C# compiler adds metadata that is used by the operating
system for loading the portable executable file or used by the run-time for
executing the contained assembly. The module option creates a module. The
metadata in the portable executable file does not include a manifest.

How can we create a constant that is an array?


You cannot create a constant that is an array since the const keyword can be
applied only to a variable whose value is known at the compile time. To prevent an
array from being reassigned, you can declare it as static readonly. However,
such arrays can be reassigned in static constructors.

What version of .NET should be used to use generics?


You need to use the version 2.0 or higher of the .NET runtime to deploy and run the
code using generics.

© Aptech Ltd Version 1.0 Page 6 of 17


Essentials of C# Programming FAQ

How can an array be resized?


Arrays created using the System.Collections.ArrayList class can be resized
dynamically. For arrays that are created without using the ArrayList class,
resizing can be done by using the in-built Resize() method of the Array class,
which re-allocates the array with a different size and copies the contents of the old
array to the new array. The following code snippet shows how an array can be
resized using the Resize() method of the Array class.

class Student
{
public static void Main()
{
int[] rollNo = { 11, 12, 13 };
string[] studentName = { "David", "Sam", "John" };
Array.Resize<int>(ref rollNo, 5);
Array.Resize<string>(ref studentName, 5);
rollNo[3] = 14;
rollNo[4] = 15;
studentName[3] = "Sandra";
studentName[4] = "Michelle";
System.Console.WriteLine("Roll No. \tStudent Name");
for (int i = 0; i < rollNo.Length; i++)
{
System.Console.WriteLine("{0}
\t\t{1}",rollNo[i],
studentName[i]);
}
}
}

How is const different from static readonly?


The value of a const field is set at the compile-time, whereas the value of the
static field is set at the run-time. This allows the class containing the static field
to modify it. However, the class can modify the static readonly field only in the
variable declaration and in the static constructors.

© Aptech Ltd Version 1.0 Page 7 of 17


Essentials of C# Programming FAQ

How can a destructor be made virtual?


The C# destructor is virtual by definition, since it is an override of the
System.Object.Finalize() method.

Can two arrays be concatenated?


Yes, two arrays can be concatenated. The following code shows how two arrays can
be concatenated into the first array:

class Company
{
public static void Main()
{
ArrayList objCustomers = new ArrayList();
ArrayList objSuppliers = new ArrayList();

objCustomers.Add("Olive Brown");
objCustomers.Add("Elvis Davis");
objCustomers.Add("Nicole Anderson");

objSuppliers.Add("Garry White");
objSuppliers.Add("Nancy Scott");
objSuppliers.Add("Carter Jason");
objSuppliers.Add("Smith Kidman");

objCustomers.AddRange(objSuppliers);
Console.WriteLine("List of customers : ");
foreach (object name in objCustomers)
{
System.Console.WriteLine(name);
}
}
}

It is also possible to copy the results, after AddRange() method is called into a
new array.

© Aptech Ltd Version 1.0 Page 8 of 17


Essentials of C# Programming FAQ

Why should the Main() method be declared as static?


The Main() method should be declared as static as it is automatically loaded by
the CLR and initialized by the run-time. If it were not declared static, then the class
would first need to be instantiated and initialized.

Is it possible to declare the override method as static when the


original method is non-static?
No, you cannot declare the override method as static. The signature and return
type of the virtual method must remain the same, only the keyword virtual is
changed to the keyword override.

Can enums, structs, or sealed classes be used as generic


constraints?
No, you cannot use enums, structs, or sealed classes as generic constraints. This is
because enums, structs, and sealed classes are non-derivable and you cannot apply
a constraint to the generic type with a type that cannot be derived.

How is a struct different from a class?


Structs are value types and do not support inheritance while classes are reference
types and can be inherited. Structs are stored in a stack while the classes are
stored on the heap.

Does C# consists of an in-built class library?


C# does not consist of an in-built class library by itself but can make use of the
in-built class library of the .NET Framework.

Can the get and set accessors of a property have different access
modifiers?
No, you cannot have different access modifiers on the get and set accessors of a
property. When a property is declared with a particular access modifier, it applies to
both the get and set accessors of the property. However, if you want them to be
different, you can create a read-only property by using the get accessor and then,
create a private or an internal set accessor that is not associated with the
property.

© Aptech Ltd Version 1.0 Page 9 of 17


Essentials of C# Programming FAQ

In an inheritance hierarchy, the destructors of which class are called


first?
The destructor of the class that has not been further inherited is called first followed
by the destructor of its parent class and so on.

What happens if I catch an exception but do not write any code


inside the catch block to handle the exception?
You must catch and handle the exceptions thrown by the try block or the throw
statement. Only exceptions that can be handled must be caught. If you catch a
particular exception and ignore to handle it, then it means you are 'swallowing the
exception'.

Why are data members of the Hashtable class stored using the
private access modifier?
Data members of the Hashtable class are stored using the private access
modifier to ensure data integrity. This allows only the member functions to access
the data members of the Hashtable class.

How is the System.Array.CopyTo() method different from the


System.Array.Clone() method?
The Clone() method creates a new array that contains all the elements present in
the original array. Here, both the arrays will contain the same elements. On the
other hand, the CopyTo() method copies the elements of an array into another
array that is already existing. Here, the array in which the elements are copied will
contain the copied elements as well as its existing elements.

If varOne.Equals(varTwo) returns true, does it imply that


varOne.GetHashcode will return the same hash code as
varTwo.GetHashcode?
No, because varOne.Equals(varTwo) returns true means the objects are equal,
not the hash codes. The hash code is unique and is independent of whether objects
are equal or not.

© Aptech Ltd Version 1.0 Page 10 of 17


Essentials of C# Programming FAQ

Is it possible for the compiler to execute multiple catch blocks for a


single try block?
No, once the appropriate catch block executes, the program control is transferred
to the finally block and then, whatever follows the block.

How is the ref modifier different from the out modifier?


The ref and out modifiers are passed along with the parameters of the method,
which means the parameter can be passed by reference. The ref modifier consists
of a parameter that is initialized while the out modifier consists of a parameter that
is not initialized.

What is the difference between managed and unmanaged code?


Code written in C# or .NET is known as managed code, whereas code written
outside them is referred to as unmanaged code. For example, C++ programs
compiled with Turbo C will be considered as unmanaged code, when they are
loaded in a .NET environment.

What is an assembly?
An assembly is a file that contains the intermediate language code. When a
particular program is successfully compiled, the C# compiler automatically
generates an assembly file, which can be either a dll (dynamic link library) file or an
executable file. An assembly is generated only once for the program and is
appropriately updated every time the program is compiled.

Can the scope of a field or method of a class to the classes in the


same namespace be restricted?
Yes, you can restrict the scope of a field or method of a class to the classes in the
same namespace by declaring the field or method using the private access
modifier.

How can we create a DLL in C#?


To create a DLL in C#, use the /target:library compiler option.

© Aptech Ltd Version 1.0 Page 11 of 17


Essentials of C# Programming FAQ

If the Console.WriteLine() method encounters a NULL character


within a string, will it stop printing the output?
No, the Console.WriteLine() method continues to print till the end of the string,
since the null values that are encountered are not considered as the end of the
string.

What is the GAC? Why is it used?


Global Assembly Cache (GAC) is a machine-wide code cache that stores assemblies
that can be shared across applications.

Can an async method have multiple await operators?


Yes, an async method can have multiple await operators. For each await
operator, the async method will stop executing until the await operation
completes.

Where can we configure the endpoint address of a WCF service?


The endpoint address of a WCF service can be configured either programmatically
or through a configuration file. It is recommended to use a configuration file
because during development it is not always possible to correctly identify in
advance the actual address (or the URL) that the service will use. In a WCF service
created in Visual Studio 2012, the endpoint address can be configured in the
App.config configuration file.

In cryptography, what is hashing?


Hashing is a cryptographic technique to ensure data integrity. Hashing can be used
to ensure that data received by a receiver has not been tampered during
transmission. Hashing ensures data integrity using a unique hash value of data,
also known as message digest. To understand the process of hashing, consider User
A, who needs to send a message to user B. User A generates a hash value of the
message and sends the hash value along with the message to user B. User B on
receiving the message generates a new hash value of the message. User B then
compares the received hash value with the new generated one. If both the hash
values match, the integrity of the message is assured.

© Aptech Ltd Version 1.0 Page 12 of 17


Essentials of C# Programming FAQ

What factors should we consider before selecting either symmetric


or asymmetric encryption to encrypt data?
Asymmetric encryption is best suited to encrypt small amount of data. You should
use symmetric encryption when the amount of data to encrypt is large, for example,
to encrypt some gigabytes of data. However, symmetric encryption is less secure as
the secret key is shared and therefore have the possibility to get intercepted and
used with malicious intent. Therefore, to encrypt large volume of data use
symmetric encryption and then, encrypt the secret key before sharing through
asymmetric encryption.

Which .NET Framework version comes with Visual Studio 2017?


.NET Framework version 4.7 comes with Visual Studio .NET 2017.

Is Visual Studio available for free?


Yes, Visual Studio 217 Community version comes free of cost. Other versions such
as Visual Studio 217 Professional and Visual Studio 217 Enterprise are paid
versions.

How is FCL different from CTS?


FCL is a comprehensive object-oriented collection of reusable types and is used to
develop applications ranging from traditional command-line to Graphical User
Interface (GUI) applications that can be used on the Web.
The CTS provides a common way to describe all supported types and establishes a
framework for cross-language execution. The CTS defines a set of rules that all
languages must follow and provides a library containing the basic primitive types,
such as Boolean, Byte, and Char that are used in application development.

Does Visual Studio 2017 support open source languages?


Yes, Visual Studio 217 supports open source languages such as Ruby, Python, and
PHP.

Why is C# preferred over C++?


C# has become a preferred programming language over C++ because of its
simplicity and user friendliness. The main advantages of C# are cross language
support, common Internet protocols, simple deployment, and XML documentation.

© Aptech Ltd Version 1.0 Page 13 of 17


Essentials of C# Programming FAQ

How is a local function better than lambda expression?


Although, a local function may seem similar to a lambda expression in its
functionality, it is much better than the latter. When creating a lambda, a delegate
must be created, which can be an unnecessary allocation. Unlike a lambda,
developers do not need to give a local function a delegate type or allocate an actual
delegate object. This makes it faster and better performing.

What is deconstruction in C#?


Deconstruction can be defined as the process of dividing a multi-part variable value
into parts and saving them into new variables.

What is the function of digital separator in C#?


In some cases where there is a need to denote a big integer or long literal in C#
code, code may not be easily readable and there are chances of error. A digit
separator, represented by an underscore (_) in C# 7.0, can be utilized within any
numeric literal so as to enhance legibility.

How is pattern matching done using switch?


With the new switch type, pattern matching can be performed based on classes or
types. Expressions can include a type name followed by a variable instance that
would be accessed within the matching case block's body. Thus, the switch
statements would no longer be limited to value types such as integers and strings.

What are the key features of C# 7.0 and 7.1?


Following are the key features of C# 7.0 and 7.1:
• Choosing the preferred language version
• Ref returns, ref locals, and improved out variables
• Improved tuples
• Improved asynchronous Main()
• Improved throw expressions
• More expression-bodied members

Are all the features of C# 7.1 made available by default to the users?
While C# 7.1 is supported by the .NET Core SDK 2.0 or Visual Studio 2017, its
features are unavailable until the user changes the language version setting for the
opened project. In other words, the user is required to modify the project’s
configuration settings for specifying the intended language version.

© Aptech Ltd Version 1.0 Page 14 of 17


Essentials of C# Programming FAQ

What is the enhancement in C# 7.1 with respect to tuples?


C# 7.1 added a minor enhancement to tuples, which is known as tuple name
inference. This new feature allows working with tuples as value types. It also
enables tuples to deduce the names of their elements from the inputs.

Where to use .NET Core?


.NET Core is a perfect fit if there is a need for a high performance and scalable
system. Microsoft suggests executing .NET Core along with ASP.NET Core to obtain
best performance and scale. .NET Core is usable if users are executing several .NET
versions side-by-side. To set up applications that have dependencies on diverse
versions of frameworks in .NET, it is best to employ .NET Core.

.NET Core can be used when the Command Line Interface (CLI) control is required.
A few users would rather prefer to work in lightweight editors and command line
control. .NET Core offers a CLI for all supported platforms and it involves minimal
installation on production machines.

.NET Core can be utilized when Docker containers are being employed. Generally,
containers and microservices architecture are used in conjunction. Due to its
lightweight and modular features, .NET Core operates well with containers. It allows
server apps to set up cross-platform to Docker containers. Though, .NET Framework
can be utilized for containers, the image size will be larger.

What is a docker?
Docker is a computer program that carries out operating-system-level virtualization,
which is referred to as containerization.

What is dependency injection?


Dependency Injection is an approach that helps in obtaining loose coupling among
objects and their dependencies. Instead of instantiating the dependencies directly
or with static references, the objects required by a class to accomplish a task are
given to the class in a certain fashion. In simpler words, Dependency Injection is
used to make applications independent of its objects or to make classes
independent of how its objects are created. Classes declare their dependencies with
the help of the constructor.

© Aptech Ltd Version 1.0 Page 15 of 17


Essentials of C# Programming FAQ

How does .NET enable working in visual form?


To work in visual form, .NET offers ADO.NET components and data-bound
control. These components can be used without extensive coding.

What is the advantage of extension method?


With extension methods, additional methods can be added to standard interfaces
without physically altering the existing class libraries and the functionality of the
existing type can be extended without modification. Thus, preventing the problems
of breaking source code in existing applications.

What is LINQ to Entities?


To create and execute queries against the conceptual model of Entity Framework,
programmers use LINQ to Entities. In LINQ to entities, a query is stored in a
variable. When the query is executed, it is first converted into a command tree
representation that is compatible with the Entity Framework. Then, the Entity
Framework executes the query against the data source and returns the result.

What is the role of an identifier in a namespace?


C# allows specifying a unique identifier for each namespace. This identifier helps
accessing the classes within the namespace.

What are the new tools in Debugger environment in Visual Studio


2017?
This environment does not usually have the Solution Explorer, Properties window,
Toolbox, and the Team Explorer. Rather, there are new debugging Windows or
tools. These include Diagnostics Tools and other details on the right, C# Interactive
and Call Stack panes at the bottom, and Locals, Watch, Exception Settings, and
Immediate Window as options at the bottom. These are all debugging tools.

How to set a breakpoint in the debugger tool?


To set a breakpoint, click the left margin of the targeted line in the code editor. This
shows a red circle in the margin. Further, the background of the entire line is
highlighted in dark brown. Alternatively, a developer can use the F9 key or select
Debug → Toggle Breakpoint with the line selected to toggle these points.

© Aptech Ltd Version 1.0 Page 16 of 17


Essentials of C# Programming FAQ

What is the use of a Data Tip?


While debugging, Visual Studio provides data tips that are informative tooltips
available only in break mode. They reveal more information about a selected
variable or an object in the present execution scope. The debugger shows the
information in a hierarchical structure. To show a data tip, insert a breakpoint and
run it in debug mode.
When execution breaks at the breakpoint, hover the mouse over a variable or an
object. This displays the associated data tip, which is a tree of members, each being
expansible to show more information related to it.

How can a package be reused by developers?


In Visual Studio 2017, the packages required for a project are installed using the
NuGet Package Manager. This extension is available both as a console and as a
Graphical User Interface (GUI). Once the extension is installed, its UI or console
window allows finding, adding, updating, and uninstalling packages to a project.
Loading the manager loads all NuGet packages from a central site and provides
options to download and add it to a project. A package is defined for each reusable
component. With NuGet Package Manager, developers can make a package
consisting of their own component and add it to the central site. This allows other
developers to use that component via NuGet.

--- End of FAQ ---

© Aptech Ltd Version 1.0 Page 17 of 17

You might also like