C# & .NET Interview Questions

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

WHAT IS THE THE DIFFERENCE BETWEEN EXE AND DLL IN C#?

1.EXE is an extension used for executable files while DLL is the extension for a dynamic link library. 2.An EXE file can be run independently while a DLL is used by other applications. 3.An EXE file defines an entry point while a DLL does not. 4.A DLL file can be reused by other applications while an EXE cannot. 5.A DLL would share the same process and memory space of the calling application while an EXE creates its separate process and memory space

What is Constructor Overloading in C#?

A Constructor can be overloaded in C#. Overloaded constructors are differentiated on the basis of their type of parameters or number of parameters. Constructor overloading is not much different than method overloading. In case of method overloading you have multiple methods with same name but different signature, whereas in Constructor overloading you have multiple constructor with different signature but only difference is that Constructor doesn't have return type in C#. Example Code

Give an example of when a delegate would be used

A delegate can be seen as a placeholder for a/some method(s). By defining a delegate, you are saying to the user of your class, "Please feel free to assign, any method that matches this signature, to the delegate and it will be called each time my delegate is called". Typical use is of course events. All the OnEventX delegate to the methods the user defines. Delegates are useful to offer to the user of your objects some ability to customize their behavior. Most of the time, you can use other ways to achieve the same purpose and I do not believe you can ever be forced to create delegates. It is just the easiest way in some situations to get the thing done.

WHAT IS THE DIFFERENCE BETWEEN ACTION AND FUNC IN C#?

Action is a delegate (pointer) to a method, that takes zero, one or more input parameters, but does not return anything. Func is a delegate (pointer) to a method, that takes zero, one or more input parameters, and returns a value (or reference). Example Code: * find attached

CAN ABSTRACT CLASS BE SEALED IN C#?

An abstract class cannot be a sealed class because the sealed modifier prevents a class from being inherited and the abstract modifier requires a class to be inherited.

What is the difference between Abstract Class & Interface in C#?

An abstract class cannot support multiple inheritance, but an interface can support multiple inheritance. Thus a class may inherit several interfaces but only one abstract class. An interface is an empty shell, just only the signatures of the methods. The methods do not contain anything. The interface can't do anything. It's just a pattern. An Abstract class is a class which will contains both definition and implementation in it. Abstract classes can have consts, members, method stubs and defined methods, whereas interfaces can only have consts and methods. Various access modifiers such as abstract, protected, internal, public, virtual, etc. are useful in abstract Classes but all methods of an interface must be defined as public. A child class can define abstract methods with the same or less restrictive visibility, whereas a class implementing an interface must define the methods with the exact same visibility. If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method. But if we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.

WHAT IS THE DIFFERENCE BETWEEN ERROR & EXCEPTION IN C#?

An exception is an Object of a type deriving from the System.Exception class. SystemException is thrown by the CLR (Common Language Runtime) when errors occur that are nonfatal and recoverable by user programs. EXCEPTION SYNTAX: try { // write your code here } Catch (exception type) { // write your code here } Errors are unchecked exception hence it is difficult to handle in code.

WHAT IS THE DIFFERENCE BETWEEN BOXING & UNBOXING?

BOXING - the conversion of value type to a reference type - stores value types in the GC Heap - is an implicit conversion - works by allocation object instance on heap and copying value into new object - the process of taking a value type, putting it inside a new object on the heap,and storing a reference to it on the stack. Example int Val = 10; Object Obj = Val; //Boxing UNBOXING - conversion of reference type to a value type - moves reference type from heap to stack - is an explicit conversion - the process of taking the item from the heap and returning a value type that contains the value from the heap. Example int Val = 1; Object Obj = Val; //Boxing int i = (int)Obj; //Unboxing NOTES - if you execute an invalid unbox operation, the runtime will throw an InvalidCastException. - when boxing and unboxing happen, you need to explicitly cast your object from a reference to a value type. - there are some performance implications with each box and unbox operation. - the boxing and unboxing operations can hurt performance; however, now that you have generic support in the .NET Framework, this is less of an issue because you can store value types in a collection without boxing them.

WHAT IS THE DIFFERENCE BETWEEN SYSTEM.CONSOLE.WRITELINE() AND SYSTEM.CONSOLE.WRITE()?

Both WriteLine() and Write() functions enable you to print information on the console in the same manner. System.console.WriteLine()prints the information on screen and goes to next line .However, System.console.Write()print the information on the screen ,but does not go to next line.

WHAT IS THE DIFFERENCE BETWEEN BUILD AND REBUILD IN C#?

Build performs an incremental build. Build will look at the files that have been modified since the last successful compile and it will only build code files which have changed. Rebuild will recompile everything.This will delete all currently compiled files (i.e., exe and DLLs) and will build everything from scratch, irrespective of if there is code change in the file or not.

WHY WOULD I USE LOCK STATEMENT IN C#?

By using the lock statement, we can ensure only one thread can be executed at any point in time. Example Code: * find attached

What is Null Coalescing Operator in C#?

C# Supports a special operator called the null coalescing operator, which returns a non-null value to an expression, in case a nullable type variable is null. The null coalescing operator "??" uses two question marks. With it you can use a custom value for a null reference variable. It simplifies null tests. Example Code CODE OUTPUT Default Csharpstar Default

What is the difference between Class and Struct?

CLASS - can support inheritance - is a reference type - is nullable - has memory overhead per new instance STRUCT - does not support inheritance - is a value type - is non-nullable - does not have memory overhead per new instance unless, it is being boxed SIMILARITIES - both compound data types meaning could have logical relationship & variables - supports methods & events - supports interfaces

WHAT IS THE DIFFERENCE BETWEEN COMPILE TIME EXCEPTION & RUN TIME EXCEPTION?

Compile time is where your compiler transforms your source code to a machine understandable language. During the compile time, it processes through various stages: - Creation of Symbol table, - Syntax analysis, - Semantic analysis, - Code optimization, - Code Generation, - Error Handling. Runtime is during the execution process(Eg: Page request is made. or looping through a variable instances, etc). Runtime errors are handles after the successful compilation. Example: The static variables are allocated with memory in the compile time. The variables that are created at runtime(during the execution process), the memory is allocated for them at run time. The compile time errors may occur with an error in syntax. This run time errors may be based on the user input like divide by zero exception, stack over flow, pointer unavailability, wrong address reference, referring null string, etc.

What is Multi-threading?

In .NET languages you can write applications that perform multiple tasks simultaneously. Tasks with the potential of holding up other tasks can execute on separate threads is known as multithreading.

IS STRING A VALUE OR REFERENCE TYPE IN C#?

In .Net Framework Strings are immutable reference types. All .net datatypes has default size except string and user type. So String is a Reference type, because it does not have default allocation size. Immutable means, it cannot be changed after it has been created. Every change to a string will create a new string. This is why all of the String manipulation methods return a string. For an example, an integer (System.Int32 ) has a fixed memory size(4 bytes) of Value range -2,147,483,648 through 2,147,483,647. Hence, an integer can be stored on the Stack (i.e. fixed memory). Alternatively, a String does not have a pre-defined memory size and it can be huge(the value range may be 0 to approximately 2 billion Unicode characters), so it requires dynamic memory allocation. When a String object is created, the actual value is stored within dynamic memory, or on the Heap. Reference types have some overhead on construction and destruction and garbage collection, because they are created on the heap. Value types on the other hand have overhead on method calls (if the data size is larger than a pointer), because the whole object is copied rather than just a pointer. Because strings can be much larger than the size of a pointer, they are designed as reference types.

What is reflection in .NET?

In .Net, during the compile time Metadata created with MSIL and stored it in a file called a Manifest . Both Metadata and Microsoft Intermediate Language together wrapped in a Portable Executable (PE) file and this can be accessed at runtime by a mechanism, called Reflection. At runtime, the Reflection mechanism uses the Portable Executable file to read information about the assembly and it is possible to uncover the methods, properties, and events of a type, and to invoke them dynamically. Reflection generally begins with a call to a method present on every object in the .NET framework, GetType(). The GetType() is a member of the System.Object class, and the method returns an instance of System.Type. Type type = refCls.GetType(); The classes in the System.Reflection namespace, together with Type, enable you to get information about loaded assemblies and the types defined within them, such as classes, interfaces, and value types.

What is a Delegate?

In the .NET environment, a delegate is a type that defines a method signature and it can pass a function as a parameter. In simple words we can say delegate is a .NET object which points to a method that matches its specific signature. A delegate is a form of type-safe function pointer used by the Common Language Infrastructure. You create a delegate with the delegate keyword, followed by a return type and the signature of the methods that can be delegated to it. Example public delegate void delegateMethod(int n1, int n2); A delegate is independent of the type of method that it references. The signature of the method and the delegate should match. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.

What is the difference between Managed & Unmanaged Code?

Managed Code Managed code is the code that is written to target the services of the managed runtime execution environment such as Common Language Runtime in .Net Technology. The Managed Code running under a Common Language Runtime cannot be accessed outside the runtime environment as well as cannot call directly from outside the runtime environment. It refers to a contract of cooperation between natively executing code and the runtime. It offers services like garbage collection, run-time type checking, reference checking etc. By using managed code you can avoid many typical programming mistakes that lead to security holes and unstable applications, also, many unproductive programming tasks are automatically taken care of, such as type safety checking, memory management, destruction of unused Objects etc. Unmanaged Code Unmanaged code compiles straight to machine code and directly executed by the Operating System. The generated code runs natively on the host processor and the processor directly executes the code generated by the compiler. It is always compiled to target a specific architecture and will only run on the intended platform. So, if you want to run the same code on different architecture then you will have to recompile the code using that particular architecture. Unmanaged executable files are basically a binary image, x86 code, directly loaded into memory. This approach typically results in fastest code execution, but diagnosing and recovery from errors might difficult and time consuming in most cases. The memory allocation, type safety, security, etc needs to be taken care of by the programmer and this will lead unmanaged code prone to memory leaks like buffer overruns, pointer overrides etc. All code compiled by traditional C/C++ compilers are Unmanaged Code. COM components, ActiveX interfaces, and Win32 API functions are examples of unmanaged code. Managed code is code written in many high-level programming languages that are available for use with the Microsoft .NET Framework, including VB.NET, C#, J#, JScript.NET etc. Since Visual C++ can be compiled to either managed or unmanaged code it is possible to mix the two in the same application.

WHAT IS THE DIFFERENCE BETWEEN YIELD & RETURN?

RETURN - Example Code * find attached RETURN - CODE OUTPUT 1 1 1 1 RETURN - CODE EXPLANATION In above example int SimpleReturn function three returns are mentioned but no matter how many times this function is called from anywhere, here from main the function will always return first value i.e. 1. YIELD - EXAMPLE CODE * find attached YIELD - CODE OUTPUT 1 2 3 YIELD - CODE EXPLANATION The only difference between yield and return is whenever yield statement is encountered in a function, the execution of function is suspended and a value is send back to the caller but because of yield whenever the function is called again, the execution of function begin where it left off previously. When resumed, the function continues execution immediately after the last yield run. Thus yield allows a function to produce a series of values over time. The only requirement for yield return statement is that the function containing yield should return an IEnumerable and no matter from where that function is called it should be called from an iteration block i.e foreach statement.

What is the difference between Stack and Heap?

Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the computer's RAM . Variables allocated on the stack are stored directly to the memory and access to this memory is very fast, and it's allocation is dealt with when the program is compiled. When a function or a method calls another function which in turns calls another function etc., the execution of all those functions remains suspended until the very last function returns its value. The stack is always reserved in a LIFO order, the most recently reserved block is always the next block to be freed. This makes it really simple to keep track of the stack, freeing a block from the stack is nothing more than adjusting one pointer. Variables allocated on the heap have their memory allocated at run time and accessing this memory is a bit slower, but the heap size is only limited by the size of virtual memory . Element of the heap have no dependencies with each other and can always be accessed randomly at any time. You can allocate a block at any time and free it at any time. This makes it much more complex to keep track of which parts of the heap are allocated or free at any given time. You can use the stack if you know exactly how much data you need to allocate before compile time and it is not too big. You can use heap if you don't know exactly how much data you will need at runtime or if you need to allocate a lot of data. In a multi-threaded situation each thread will have its own completely independent stack but they will share the heap. Stack is thread specific and Heap is application specific. The stack is important to consider in exception handling and thread executions.

What is the execution entry point for a C# Console Application?

The Main method is the entry point of a C# console application or windows application. When the application is started, the Main method is the first method that is invoked.

What is the difference between a Thread and a Process?

The processes and threads are independent sequences of execution, the typical difference is that threads run in a shared memory space, while processes run in separate memory spaces. A process has a self contained execution environment that means it has a complete, private set of basic run time resources purticularly each process has its own memory space. Threads exist within a process and every process has at least one thread. Each process provides the resources needed to execute a program. Each process is started with a single thread, known as the primary thread. A process can have multiple threads in addition to the primary thread. On a multiprocessor system, multiple processes can be executed in parallel. Multiple threads of control can exploit the true parallelism possible on multiprocessor systems. Threads have direct access to the data segment of its process but a processes have their own copy of the data segment of the parent process. Changes to the main thread may affect the behavior of the other threads of the process while changes to the parent process does not affect child processes. Processes are heavily dependent on system resources available while threads require minimal amounts of resource, so a process is considered as heavyweight while a thread is termed as a lightweight process.

WHAT IS THE DIFFERENCE BETWEEN VAR AND DYNAMIC IN C#?

VAR - introduced in C# 3.0 - statically typed i.e. the type of variable is decided at compile time - it is required to be initialized at the time of declaration e.g. var str = "string"; - errors are caught at compile time - intellisense is available DYNAMIC - introduced in C# 4.0 - dynamically typed i.e. the type of variable is decided at run time - it does not require initialization at the time of declaration e.g. dynamic str; - errors are caught at run time - intellisense is NOT available

WHAT IS THE DIFFERENCE BETWEEN WEB.CONFIG, APP.CONFIG & MACHINE.CONFIG file?

WEB.CONFIG - it is used for asp.net projects or web services - by default, it has several configurations required for the web application - it is also known as 'APPLICATION LEVEL CONFIGURATION FILE' - it inherits its setting from MACHINE.CONFIG file - it is parsed at run-time therefore if edited, the application auto loads changes made - it is automatically generated when a new web application project is created - more than 1 web.config file can exist within an application - it is a required file for ASP.NET web pages APP.CONFIG - it is used for windows forms, windows services, console apps and WPF applications - it is parsed at compile time therefore if edited, the application has to be restarted for changes to be reflected - it is not automatically added when the applicatio project is created - there can only be 1 app.config file for a window application - it is optional in a windows application MACHINE.CONFIG - this file is automatically installed on the developers system following a successful installation of Visual Studio - it is also known as Machine Configuration File - there can only be 1 of these existing per computer system - it has the highest level in the configuration hierarchy - the settings included within this file are applied to all web applications residing on the server - this file is overriden by web.config file - without this file, the web application cannot be executed.

CAN CLASS EXISTS WITHOUT NAMESPACE?

Yes, it would be under global namespace.

What is the difference betwwen INT & INT32?

int is a primitive type allowed by the C# compiler, whereas Int32 is the Framework Class Library type (available across languages that abide by CLS). In fact, int translates to Int32 during compilation.They are Synonymous.


Ensembles d'études connexes

N121 PrepU Ch. 11: Drug Therapy for Hematopoietic Disorder

View Set

Hinkle Chapter 13: Fluid and Electrolytes: Balance and Disturbance

View Set

Jurisprudence & Nurse Practice Act/Professional Nursing

View Set

Possessive Adjectives (Unit 1: You and Me)

View Set

Upper Extremity 2: Elbow, Humerus

View Set

Basic EMT Fall Session Chapter 15

View Set

CSC 205 AB Module 3 Quiz : Inheritance and Abstract classes

View Set