C# Part2
C# Part2
What is C#?
C#, released in 2000, is a C-based programming language used for everything from desktop
applications to web services. Today, C# is one of the most popular programming languages in
the world — and it’s a language that is highly sought after in the programming field.
C# differs from C++ in a few major ways. The most obvious is that C# is a component-based
language, whereas C++ is an object-oriented language. C# is considered to be more heavyweight
than C++, but it’s used in many modern systems, such as game development kits.
1. What is a class?
//data members
//function
//login of function
}
2. What are the main concepts of object-oriented programming?
Encapsulation, abstraction, polymorphism, and inheritance are the main concepts of object-
oriented programming. Be prepared to describe each of these. Object-oriented programming
differs from procedural programming insofar as procedural programming happens
chronologically, step-by-step, whereas object-oriented programming is far more flexible.
3. What is an object?
An object is an instance of a class through which we access the functions of that class. We can
use the “new” keyword to create an object. A class that creates an object in memory holds
information about the functions, data members, and behavior of that class.
//Class
//private members
//function
fName = firstName;
lName = lastName;
}
}
class Program
//this is object
[Link]("John", "Grande");
[Link]();
A constructor is like a method with the same name as the class, but it is a unique method. Even
if it is not created, the compiler creates a default constructor in memory at the time of creating
an object of the class.
The constructor is used to initialize the object with some default values.
Default constructor, parameterized constructor, copy constructor, static constructor, and private
constructor are all different constructor types.
//default constructor
public Student()
{
//parameterized constructor
[Link] = rNum;
[Link] = fName;
//static constructor
static Student()
//copy constructor
rollNumber = [Link];
fullName = [Link];
~Purchase()
C# is managed code because Common Language Runtime compiles the code to intermediate
language code. C++ would provide examples of unmanaged code. Managed code simply refers
to code that has its execution managed by the runtime.
We can categorize variables into value type and reference type. Variables of value type contain
the value directly while a reference type variable contains the reference of the memory address
where the value is stored actually in the memory.
A namespace is a way of organizing classes of the same group or functionality under the same
name. We can call it a module. Although it is not compulsory to put class in a namespace.
namespace demoapp
class SomeClass
[Link]("Creating my namespace");
XML comments
Encapsulation is a process of wrapping function and data members together in a class; it’s like a
capsule, a single unit.
class User
get
return address;
set
address = value;
}
get
return name;
set
name = value;
class MyProgram
[Link] = "Ravi";
[Link]();
Abstraction is the method of exposing only the required features of the class and hiding
unnecessary information.
A rider knows the color, name, and model of the bike. Still, they do not know the internal engine
and exhaust functionality. Likewise, abstraction focuses on providing access for a specific
functionality without exposing how that functionality works internally.
Polymorphism means the same method but different implementation. There are two types of
polymorphism.
[Link]("Using keypad");
[Link]("Using keypad");
//method override
An interface is another form of an abstract class that has only abstract public methods. These
methods only have the declaration and not the definition. A class implementing the interface
must have the implementation of all the methods of the interface.
For example:
interface IPencil
{
void Write(string text);
[Link]("Using keypad");
The ability to inherit characteristics from classes makes the entire process of managing classes
much easier, as you can create subclasses that are customized. The originating class will be
called either a parent class or base class.
[Link]("calling...!");
class MyProgram
[Link]();
15. How would you implement multiple interfaces with the same method name in the same
class?
To implement multiple interfaces with the same method name, you would avoid
implementation within the body of the function. Instead, you would explicitly provide the name
of the interface to the body of the method. The compiler will understand which interface
methods are being referred to, therefore resolving the issue.
interface myInterface1
void Print();
interface myInterface2
void Print();
myInterface2
void [Link]()
}
void [Link]()
16. What is the virtual method and how is it different from the abstract method?
A virtual method must have a default implementation, and we can override this virtual method
using the override keyword in the derived class.
The abstract method is without implementation and is created inside the abstract class only. In
the case of an abstract class, the class derived from the abstract class must have an
implementation of that abstract method.
}
Here’s an example of an abstract method:
//function override
[Link]("Using keypad");
//function override
Method overriding is when we override the virtual method of a base class in the child
class using the override keyword.
We use the static keyword to create a static class, a static method, or static properties.
When we create a static class there can be only static data members and static methods in that
class.
Static means that we cannot create the instance of that class. That class can be used directly like
[Link].
When there is a need for special functions, which are typical for all the instances of other
classes, then we use static class.
For example, there is a requirement to load some default application-level values. We create a
static class with static functions. That class is then accessible to all other classes without
creating any instance. It also shares the same data with all the classes.
int maxAmount = 0;
//code to fetch and set the value from config or some file.
return maxAmount;
{
//not required to create an instance.
No.
“This” cannot be used with a static class because we can only use static variables and static
methods in the static class.
Constant variables have to be assigned a value at the time of declaration only, and we
cannot change the value of that variable throughout the program.
We can assign the value to the read-only variable at the time of declaration or in a
constructor of the same class.
using System;
namespace demoapp
class DemoClass
// Constant fields
using System;
namespace demoapp
class MyClass
// readonly variables
// Using constructor
myvar1 = b;
myvar2 = c;
[Link]("Display value of myvar1 {0}, " +
// Main method
21. What is the difference between string and string builder in C#?
A string is an immutable object. When we have to do some actions to change a string or append
a new string it clears out the old value of the string object, and it creates a new instance in
memory to hold the new value in a string object. It uses [Link] class, for example.
using System;
namespace demoapp
class StringClass
val += "World";
[Link](val);
}
}
StringBuilder is a mutable object, meaning that it creates a new instance every time for the
operations like adding string (append), replace string (replace). It uses the old object only for
any of the operations done to the string and thus increases the performance. It uses
[Link] class, for example.
using System;
using [Link];
namespace demoapp
class StringClass
[Link]("World");
[Link](val);
We can use continue and break statements in a loop in C#. Using a break statement, we can
break the loop execution, while using the continue statement, we can break one iteration of the
loop.
using System;
namespace demoapp
class LoopingStatements
{
if (i == 4)
[Link]();
using System;
namespace demoapp
class LoopingStatements
if (i == 4)
{
[Link]();
Conversion of value type datatype to reference type (object) datatype is called boxing.
For example:
namespace demoapp
class Conversion
int i = 10;
object o = i;
For example:
namespace demoapp
{
class Conversion
object o = 222;
int i = (int)o;
We use a “sealed” keyword to create a sealed class. Classes are created as a sealed class when
there is no need to inherit that further or when there is a need to restrict that class from being
inherited.
There is a feature in the C# language to divide a single class file into multiple physical files. To
achieve this, we have to use the “partial” keyword. At compile time, it is logically one file only;
we cannot have a method with the same name or a variable with the same name in two
different partial class files.
Here, to facilitate the developers to break down the big class files into multiple small physical
files, this feature is provided.
An enum can be int, float, double, or byte. But if it’s not an int, explicit casting is required.
The .NET framework enum can be used to create a numeric constant. Int is the default of the
enumeration element. By default, the first enumerator has the value 0, and each successive
enumerator is increased by 1, much like an array.
Dependency injection is a design pattern. Instead of creating an object of a class in another class
(dependent class) directly, we are passing the object as an argument in the constructor of the
dependent class. It helps to write loosely coupled code and helps to make the code more
modular and easy to test.
Constructor injection: This is the most commonly used Injection type. In constructor
injection, we can pass the dependency into the constructor. We have to make sure that
we do not have a default constructor here, and the only one should be a parameterized
constructor.
Property injection: There are cases when we need the default constructor of a class, so
in that case, we can use property injection.
Method injection: In method injection, we need to pass the dependency in the method
only. When the entire class does not require that dependency, there is no need to
implement constructor injection. When we have a dependency on multiple objects, then
instead of passing that dependency in the constructor, we pass that dependency in the
function itself where it is required.
The keyword “using” is used to define the scope of the resources used in that using statement
block. All the resources used inside the using code block get disposed of once the code block
completes execution.
_name = name;
_price = price;
class Students
[Link]();
Access modifiers are keywords used to provide accessibility to a class, member, or a function.
Delegates are like function pointers, it is a reference data type that holds the reference of a
method. We use delegates to write generic type-safe functions. All delegates derive from
[Link].
A delegate can be declared using the delegate keyword followed by a function signature, as
shown below.
Delegates have a signature as well as return type. A function assigned to delegates must
be fit with this signature
Delegate objects, once created, can dynamically invoke the methods it points to at
runtime
Get a subscription to a library of online courses and digital learning tools for your organization
with Udemy Business.
Request a demo
using System;
namespace demoapp
class DelegateClass
// declare delegate
// or
printDel(200);
printDel = PrintMoney;
printDel(10000);
printDel(200);
Multicast delegates can invoke multiple methods. The delegate method can do
multicasting. We can add a method in the delegate instance using + operator, and we
can remove a method using – operator. All the methods are invoked in sequence as they
are assigned.
Generic delegates are introduced by .Net Framework 3.5. There is no need to create an
instance in a generic delegate.
The array stores the value of the same type. It is a collection of variable stores into a memory
location.
For example:
Arrays can have more than one dimension. Multi-dimensional arrays are also called rectangular
arrays.
For example:
Using the Clone() method, we can create a new array object containing all the elements of the
original array and using the CopyTo() method. All the items of existing array copies into another
existing array. Both ways create a shallow copy.
An array and ArrayList are similar. When you want to store items of the same type, you can use
an array. An array has a fixed size. When you want to store any type of data, we use an ArrayList.
An ArrayList doesn’t have a fixed size.
using [Link];
namespace demoapp
class Sample
country[1] = "Denmark";
country[2] = "Russia";
[Link](3);
[Link]("USA");
[Link](false);
A jagged array is like a nested array where each element of a jagged array is an array in itself.
The item of a jagged array can be of different dimensions and sizes.
A jagged array is a special type of array introduced in C#. A jagged array is an array of an array in
which the length of each array index can differ.
namespace demoapp
Class and struct are both user-defined but have significant differences.
A struct inherits from [Link] type, thus it’s a value type. Structs are preferable when
there is a small amount of data. A structure cannot be abstract. There is no need to create an
object with a new keyword. Struct does not have permission to create any default constructor.
Syntax of struct:
struct MyStruct
A class is a reference type in C#, and it inherits from the [Link] Type. When there is a
large amount of data, classes are used. We can inherit one class from another class. A class can
be an abstract type.
The “throw” statement will keep the original error stack of the previous function, while the
“throw ex” statement will retain the stack trace from the throw point. Usually, it’s advised to
use “throw” because it provides exact error information and trace data.
Finalize is a method called just before garbage collection. The compiler calls this method
automatically when not called explicitly in code.
Thus, finally is related to execution handling, whereas finalize is used relative to garbage
collection.
We can declare the var type of a variable without specifying the .net data types explicitly. The
compiler automatically detects the type of a variable at the compile-time based on the value
assigned to it. We cannot declare a var type variable without assigning a value to it. The value of
the var type variable cannot be changed later in the code.
Dynamic is the opposite of var. We can change the value of a variable of type dynamic in the
code later. It also decides the type of the variable based on the value assigned to it.
Like at the time of creating a variable of type dynamic, a value of integer type is assigned to it,
then also in the code further, we can assign a string type value to that variable. It holds the last
changed value and acts like the data type of the latest values it holds.
public Bike()
someValue = "Hello";
In the above example, if we declare the variable “someValue” to type var instead of dynamic, it
throws an error. The reason for that error is that in the next line, we changed the value of the
variable and assigned a string value.
Advanced C# Programming Questions
Sometimes we may need to create a new type without defining it. This will be known as an
anonymous type. This is helpful when there is a need to define read-only properties in a single
object without defining each type.
Here, a compiler generates type and is accessible only for the current block of code.
FirstName = "John",
SurName = "lastname"
};
Any code block in C# runs in a process called a thread. A thread is the execution path of the
program. Simple applications can run on a single thread, but today’s programs frequently use
multithreading. Multithreading divides the execution of the process among multiple threads to
execute it simultaneously and, consequently, more efficiently.
Through multithreading, we can run more than a single task at a time. Programs are more
efficient and fast. But we also need to understand how threads work.
Each thread has its lifecycle, which includes various states of thread:
Unstarted State: In this state, the compiler creates the instance of the thread but waits
for the start method.
Started: It is the state when the thread is ready to run and waiting for the CPU cycle.
Exception handling is managed through a try, catch, finally, and throw model. These are the
keywords used throughout the model.
Try: We keep the code in the try block for which we want to handle the exception.
Catch: When any exception occurs in a try block, then it is caught in a catch block with
the help of an exception handler.
Finally: To execute a code block irrespective of error, we place that code in the finally
block to get executed.
try
catch (Exception)
{
throw;
finally
Custom exceptions are used for errors that are being caught per user requirements rather than
built into the compiler. Custom exceptions are an easy way to instance user-defined exceptions.
if (quantity == 0)
LINQ refers to Language INtegrated Query. LINQ is a method of querying data using .NET
capabilities and a C# syntax that’s similar to SQL.
The advantage of LINQ is that we can query different sources of data. The data source could be
either a collection of objects, XML files, JSON files, in-memory data or lists or database objects.
We can easily retrieve data from any object that implements the IEnumerable<T> interface.
"Iphone","Samsung","Nokia","MI"
};
//linq syntax
where [Link]("Nokia")
select s;
When we want to send an object through a network, then we have to convert that object into a
stream of bytes. Serialization is the process of converting an object into a stream of bytes. To
facilitate the object for serializable, it should implement ISerialize Interface. The process of de-
serialization is the reverse process of creating an object from a stream of bytes.
Generics in C#:
increase performance.
Generics encourage the usage of parameterized types as seen in the example below:
using System;
namespace demoapp
private T data;
//using properties
public T value
/using accessors
get
return [Link];
set
[Link] = value;
}
}
//vehicle class
class Vehicle
//Main method
[Link] = 6.0F;
[Link]([Link]);
//display 6
[Link]([Link]);
Assembly name
Class name
Method name
Object type
A null value can be assigned to a variable in C#. These types are called nullable types. Most
variable types are nullable types.
Example below:
namespace demoapp
class Calculate
number = num;
if ([Link])
//do something
}
49. Which is the parent class of all classes which we create in C#?
[Link].
A programmer writes code that is readable to people. That code is then fed into a C# compiler.
The C# compiler will compile the code into efficient, machine-readable, managed code, known
as bytecode. Then, the Just in Time Compiler (JIT) will compile the bytecode into native or
machine language. When the program is run, it is this code that will be directly executed by the
CPU.
A hashtable is a collection of pairs, generally “keys” and “values.” Frequently, you will hear
about “hashtables” in regards to passwords; a password hash can be created for a given
password. But a hashtable itself is just a general-purpose collection of key objects and value
objects, in which the values have to be accessed using the keys; they cannot be accessed
otherwise.
52. How can you create a derived class object from a base class?
This is a trick question! You cannot. A derived class will inherit variables and methods from the
base class. Further, a derived class can have only a single base class. You would need to do your
work with your base class directly.
An immutable string is an object that cannot be changed, although you can change the
reference to it. In general, an immutable string should be used whenever you have a constant
that absolutely should not be changed. However, you should use this trick sparingly because an
immutable string may throw an error if you try to change it later.
Reflection refers to methods and processes by which a system is able to look at and modify
itself. In C#, reflection would refer to inspecting the contents of a system. It needs to be
included manually within C# through the “[Link]” namespace. Reflection is
particularly useful to debugging tools.
A generic class is a class that can handle any type. This is unique because most classes follow
strict typing; you have to declare a type, and that type has to be consistent. Defining a generic
class would go as follows:
class dataStore<T> {
public T data {
get; set;
By using the params keyword, you can specify a method parameter that takes a variable number
of arguments. The parameter type must be a single-dimensional array.
int sum =0
sum+=list[i];
NuGet is a package manager for developers. It enables developers to share and consume useful
code. A NuGet package is a single ZIP file that bears a .nupack or .nupkg filename extension and
contains .NET assemblies and their needed files.
58. What are DLL files, and what are the advantages of using them?
A DLL is a library that contains code and data that can be used by more than one program at the
same time. Each program can use the functionality that is contained in a DLL. This helps
promote code reusability and efficient memory usage.
By using a DLL, a program can be modularized into separate components. Because the modules
are separate, the load time of the program is faster. And a module is only loaded when that
functionality is requested.
Additionally, updates are easier to apply to each module without affecting other parts of the
program. When these changes are isolated to a DLL, you can apply an update without needing
to build or install the whole program again.
POCO stands for Plain Old CLR Objects. A POCO is a class that doesn’t depend on any
framework-specific base class. It is like any other normal .NET class. Hence the name Plain Old
CLR Objects. These POCO entities (also known as persistence-ignorant objects) support most of
the same LINQ queries as Entity Object derived entities.
A Data Transfer Object (commonly known as a DTO) is usually an instance of a POCO (plain old
CLR object) class used as a container to encapsulate data and pass it from one layer of the
application to another. You would typically find DTOs being used in the service layer (backend)
to return data back to the presentation layer (frontend).
Referring to the above questions and answers gives us in-depth knowledge of all essential
concepts of C# language. These technical answers can help to sharpen our knowledge and help
to increase our comprehension of the language. If you need to brush up on C#, a bootcamp or
refresher course can help.