• Shuffle
    Toggle On
    Toggle Off
  • Alphabetize
    Toggle On
    Toggle Off
  • Front First
    Toggle On
    Toggle Off
  • Both Sides
    Toggle On
    Toggle Off
  • Read
    Toggle On
    Toggle Off
Reading...
Front

Card Range To Study

through

image

Play button

image

Play button

image

Progress

1/377

Click to flip

Use LEFT and RIGHT arrow keys to navigate between flashcards;

Use UP and DOWN arrow keys to flip the card;

H to show hint;

A reads text to speech;

377 Cards in this Set

  • Front
  • Back
When do you absolutely have to declare a class as abstract?
1. When the class itself is inherited from an abstract class, but not all base abstract methods have been overridden.2. When at least one of the methods in the class is abstract.
Which of the following is Mutable?
NOTE: This is objective type question, Please click question title for correct answer.
How can we clear Cache stored in browser ?
Below mentioned code is useful to clear the Cache stored in the Browser.Response.ExpiresAbsolute = DateTime.Now;Response.Expires = -1441;Response.CacheControl =no-cache;Response.AddHeader(Pragma,no-cache);Response.AddHeader(Pragma,no-store);Response.AddHeader(cache-control,no-cache);Response.Cache.SetCacheability(HttpCacheability.NoCache);Response.Cache.SetNoServerCaching();NoteThis code is useful only when the caching is done in the server.
What is operators in C# and how many types of operators are there in c#?
C# has a large set of operators, which are symbols that specify which operations to perform in an expression.Arithmetic+ - * / %Logical (boolean and bitwise)| ^ ! ~|| true falseString concatenation+Increment, decrement++ --ShiftRelational== !===Assignment= += -= *= /= %== |= ^===Member access.Indexing[]Cast()Conditional?:Delegate concatenation and removal+ -Object creationnewType informationas is sizeof typeofOverflow exception controlchecked uncheckedIndirection and Address* -[]For more details visithttp://msdn.microsoft.com/en-us/library/6a71f45d(VS.71).aspx
What is object pooling?
Object Pooling is something that tries to keep a pool of objects in memory to be re-used later and hence it will reduce the load of object creation to a great extent.Object Pool is nothing but a container of objects that are ready for use. Whenever there is a request for a new object, the pool manager will take the request and it will be served by allocating an object from the pool.This concept has been better explained in following articlehttp://www.c-sharpcorner.com/UploadFile/vmsanthosh.chn/109042007094154AM/1.aspx
What is OUT Keyword ?
Out keyword is used for passing a variable for output purpose. It has the same concept of ref keyword. Passing a ref parameter needs variable to be initialized while out parameter is passed without initialized.It is useful when we want to return more than one value from the method.Example:class Test{public static void Main(){int a; // may be left un-initializedDoWork(out a); // note outConsole.WriteLine(The value of a is+ a);}public static void DoWork(out int i) // note out{i=4; //must assigned value.}}The program will result : The value of a is 4
Write a single line of code to create a text file and write contents into it.
Use following codeSystem.IO.File.WriteAllText(@c:\MyTextFile.txt,MyContents);
Difference between typeof and Type.GetType
typeof and Type.GetType both help us to get Type Information using Reflection.Differences:typeof:1)typeof expects only an existent typename.2)Namespace reference is not needed.3)typename is verified at the compile time itselfex: Type t=typeof(Program);Type.GetType1))we have to specify a typename, which will be checked at runtime only.if it does not exist, an exception will be generated.2)Namespace is needed before the type nameex: Type t=Type.GetType(System.String);
What is IDisposable interface in .NET?
IDisposable interface is used to release the unmanaged resources in a program.The garbage collector has no knowledge of unmanaged resourcessuch as window handles, or open files and streams.To release these type of resources we make use of the Dispose method by implementing the IDisposable interface.IDisposable interface, defines a single method named Dispose():public interface IDisposable{void Dispose();}
Write the difference between Stack and Heap?
Stack:• Memory will be allocated at the compile time.• Here the memory is allocated by the compiler.• Memory will be allocated only in sequential locations.• The memory will also be deleted by the compiler.• There is lot of chance of memory wastage.Heap:• Memory will be allocated at the run time.• Here the memory is allocated by the user.• Memory will be allocated in sequential locations and non- sequential locations.• The memory must be deleted explicitly by the user.• There is no chance of memory wastage if the memory is handled perfectly.
Explain two different scenarios where the Static Constructors can be used ?
These are the 2 different scenarios where the Static Constructor can be used :When ever the Class uses the log file and a constructor is used to write some contents into this file.These Static Constructors are also used when we create Wrapper Classes for the un-managed code and when the constructor can call the load library method.
What is difference between readonly and const variable?
A const field can only be initialized only at declaration time of that field but readonly field can be initialized at the time of declaration or in constructor also. a const field will have only one constant value but readonly field can have different value depending on teh constructor.Readonly is runtime ocnstant and cons field is compile time constant.Example:public class example{public const int i = 20;i=30;//compile time error.public readonly int j=20;//initialized at declaration.public readonly int l;public example(){l=30;//readonly field initialized in constructor also.}}
Can we have statid indexers in C#?
No, indexers are never static in C#.Indexers always need an object reference to assign or retreive data from arraysor collections.example:class abc{int[] arr=new int[2];//indexer is defined like thisint this[int a]{get{return arr[a];}set{arr[a]=value;}}static void Main(){abc p=new abc();//call to indexers set block.p[0]=100;//get blockConsole.WriteLine(p[0]);}}}
What is Type Inferencing?
The Type Inferencing is a technique which is used to get the data type of thevariable that is determined by the compiler on the basis of the value assigned to thevariable.The variable must be declared using the var keyword and shouldnt havenull values. The variable should also be assigned some value and the declarationshould be method level.Like var value=100;But we cant mention like var value=null;
Difference between String and String Buffer in c#?
String..1.Its a class used to handle strings.2.Here concatenation is used to combine two strings.3.String object is used to concatenate two strings.4.The first string is combined to the other string bycreating a new copy in the memory as a string object, andthen the oldstring is deleted5.we sayStrings are immutable.6.When using concatenation consumes more memory.String Builder..1.This is also the class used to handle strings.2.Here Append method is used.3.Here, Stringbuilder object is used.4.Insertion is done on the existing string(no new memory is allocated)5.Usage of StringBuilder is more efficient in case largeamounts of string manipulations have to be performed6.Consumes less memory when compared to String, if we add the characters to the string in future.
How can we check files exists in a physical directory ?
We can check whether a particular file is existing in a physical directory or not by using this codeSystem.IO.File.Exists(path). pathThis is the physical file path and it will return you a Boolean value so that we can check whether a file is existing or not
What for using System.Logging namespace is used ?
It is used to track the info about , when the particualt application got errorsome. It helps to redirect to the developer inorder to correct those.
Stack is collection where elements are processed in
NOTE: This is objective type question, Please click question title for correct answer.Found this useful, bookmark this page link to the blog or social networking websites.
Are private class-level variables inherited?
Yes, but they are not accessible. Although they are not visible or accessible via the class interface, they are inherited.
Why should boxing be avoided?
NOTE: This is objective type question, Please click question title for correct answer.
What is the basic difference between a "const" and "readonly" in C#?
const=constvariables are implicitly static and they must be defined when declared. Example :-privateconstint testVariable = 500;In the above code, a constant variable is declared and defined in the same time. If you dont initialize aconstvariable then it will results in compilation error.readonly= Thereadonlykeyword is a modifier that you can use on fields. When a field declaration includes areadonlymodifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.publicreadonlyint i = 5;Example :-class MyTestClass{public readonly int i;public MyTestClass(){i = 100; // Initialize a readonly instance field}}Inreadonly, either you initialize in the declaration statement or you initialize it via a constructor.I hope the above code samples are clear.Thanks and RegardsAkiii
Can multiple catch blocks be executed for a single try statement? In other words if a body of a catch block is executed can code inside another catch block also be executed
NOTE: This is objective type question, Please click question title for correct answer.
What is a collection?
A collection serves as a container for instances of other classes. All classes implement ICollection interface which intern implement IEnumerable interface.
What does assert() method do?
In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.Found this useful, bookmark this page link to the blog or social networking websites.
Is there any Supplement of exit() method or quitting a C# application ?
Yes we can, by usingSystem.Environment.Exit(int exitProgram)or we can even useApplication.Exit()if it is a windows application
Which methods are used to execute javascript code from code behind file?
RegisterStartupScript and RegisterClientScriptBlock
What is Zero-Width Assertions in C#?
With the help of Regular Expression languages, you can place conditions on what it should occur before and after a match, through lookbehind, lookahead, anchors, and word boundaries. They don’t increase the width or length of the match. So that’s why these are called Zero-Width Assertions.
Is String is Value Type or Reference Type in C#?
String is an object (Reference Type).
Can we call a base class method without creating instance ?
Yes,It is possible,1) If it is a static method.2) By inheriting from that class.3) From derived classes using base keyword.
What is an Array?
An array is a collection of related instance either value or reference types. Array posses an immutable structure in which the number of dimensions and size of the array are fixed at instantiation.C# Supports Single, Mult dimensional and Jagged Array.Single Dimensional Array:it is sometimes called vector array consists of single row.Multi-Dimensional Array:are rectangular&consists of rows and columns.Jagged Array:also consists of rows&columns but in irregular shaped (like row 1 has 3 column and row 2 has 5 column)
What is the default modifier for the class member?
NOTE: This is objective type question, Please click question title for correct answer.
Mention two cases where static constructors can be used?
• When the class is using a log file and the constructor is used to write data and enters into the file then we can use static constructor.• It is also useful to call the LoadLibrary method by using constructors and when creating wrapper classes for unmanaged code.
Which is the Best one for using String concatenation?
NOTE: This is objective type question, Please click question title for correct answer.
What is the preferred model for event handling in C#?
NOTE: This is objective type question, Please click question title for correct answer.
What is the use of Standard Query Operators in LINQ?
Basically these are used in LINQ to work with collections for the following...• To get total count of elements in a collection.• To order the results of a collection.• For grouping.• For computing average.• To join two collections based on matching keys.• To filter the results
Show how you specify nested classes as partial classes with example?
The nested classes can be specified as a partial class even if the containing class is not partial. Below is one example.class ClsContainer{public partial class Nested{void App1() { }}public partial class Nested{void App2() { }}}
Can we specify the access modifiers for the get and set accessors in a property?
Yes, we can specify the access modifiers for the get and set accessors in a propertyExample:internal string myname{private set;get;}This is OkNote:1)The access modifier for the accessor must be more restrictive than that of the property.private is more restrictive than internal.2)Both get and set accessors cannot have access modifiers in the same property.private set and private get would be WRONG in the above example.
Which of the following class does not belong to Collection namespace ?
NOTE: This is objective type question, Please click question title for correct answer.
How will you use Take and Skip extension method to judiciously do batch operation?
Say we have a bulk of records(take 40 for example sake). Now let us do a batch operation for 10 records each time. The program will bevar intList = new Listint();Enumerable.Range(1, 40).ToList().ForEach(i =intList.Add(i));int setRecordCount = 10;//Pick the records from 1 - 10var record1To10 = intList.Skip(setRecordCount * 0).Take(setRecordCount);//Pick the records from 11 - 20var record11To20 = intList.Skip(setRecordCount * 1).Take(setRecordCount);//Pick the records from 21 - 30var record21To30 = intList.Skip(setRecordCount * 2).Take(setRecordCount);//Pick the records from 31 - 40var record31To40 = intList.Skip(setRecordCount * 3).Take(setRecordCount);In the first case, we are skipping no records and picking up the first 10 records from the original 40 records. In the second case, we are first skipping the 10 recordfrom the entire 40 records. So from the remaining 30 records(i.e. 11 to 40), we are picking up the first 10 records i.e. 11 to 20.A similar explanation follows for the rest of the two cases also.
When to use Public and Private access modifiers
Using proper access modifiers is the key of writing good Object Oriented Programming.Below are few of the points that should be taken care while using Public and Private access modifiersPrivate1. A member that are used within a class should be private.2. If you are refactoring a lengthy method in a class, the re-factored method should be declared as private as you are not intending to reuse that method again.3. Any member that has some sensitive information or calculations should be controlled by using private and it should be exposed properly through a public member.Public1. Frequently used methods should be public.2. The methods of different layers that are intended to pass data between layers should be declared as public.3. Generally properties in C# is declared as public as it is intended to use by anyone.4. Method that gets and sets the value of private data should be public. (For example, Properties)
What is the use of default keyword?
It is used in 2 contexts.1)With theswitchstatement.example:Console.WriteLine(enter number);int a=Int32.Parse(Console.ReadLine());switch(a){case 100:Console.WriteLine(correct);break;default:Console.WriteLine(100 is right value);break;}2) Provide default values for value types (which is 0) and null value as the default valuefor the reference types:example: int a=default(Int32);default for a will be 0.
How can we disable the context menu for a textbox control?
The Textbox class contains theContextMenuStripproperty. When we set this property to a dummy instance of theContextMenuclass, the textbox control is unable to provide any context menu on the right click of the mouse.
How will you make a combination of the Enum values in C# ? Explain with an example.
In C#, we have to decorate the Enum withFlag attributeand use abitwise operatorto make a combination of the values.Let us look at the below exampleclass Program{static void Main(string[] args){Console.WriteLine(Fruits.AllFruits.HasFlag(Fruits.Guava));Console.ReadKey();}[Flags]enum Fruits{Apple = 1,Mango = 2,Banana = 3,Guava = 4,AllFruits = Apple | Mango | Banana | Guava,AppleANDGuava = AppleGuava}}/* Result */TrueWe are checking if the Guava is present in theAllFruitsenum.
Write an equivalent of exit() for quitting a C# .NET application?
Yes, in case of windows forms application you can exit the application with the help of System.Environment.Exit(datatype exitCode) or Application.Exit().
can we create instance of an abstract class?
No, we can not create instance of an abstract class.Example:abstract class abstractExample{public abstract void func1();}class derivedClass : abstractExample{public override void func1(){//your code here.....}}if you will try to create instance, it will give error.abstractExample objAbstract=new abstractExample();//error in this line.
How You Can create a string reference?
NOTE: This is objective type question, Please click question title for correct answer.
What does the
This window is used to show the Objects instance data.It points to the object that is pointed to by this reference.
What is UDP and how does it work?
TheUserDatagramProtocol (UDP) provides an unreliable datagram-orientedprotocol on top of IP.The delivery and order of datagrams are not guaranteed.It is connection-less, that is, a UDP application does not have to connectexplicitly to another. Datagrams are simply sent or received.
What are Destructors?
Destructors are used to destruct instances of classes.Destructors cannot be defined in structures, they are only used with classes.A class can only have one destructor.Destructors cannot be inherited or overloaded.Destructors cannot be called, they are invoked automatically.A destructor does not take modifiers or have parameters.Example:class Car{~ Car() // destructor{// cleanup statements...}}
Can we throw exception from catch block ?
Yes.The exceptions which cant be handled in the defined catch block are thrown to its caller.
Where the global assembly cache located on the system?
Usually the global assembly cache located at C:\winnt\assembly or C:\windows\assembly.
What’s the C# syntax to catch any possible exception?
A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.
In which cases you use override and new base ?
You can use the new modifier to explicitly hide a member inherited from a base class.To hide an inherited member, you have to declare it in the derived class using the same name, and modify it with the new modifier.
With strict conversions enabled, which of the following would allow an implicit conversion?
NOTE: This is objective type question, Please click question title for correct answer.
Does interface have access modifier?
Interface has public modifier by default but you are not allowed to specify any access modifier in interface.Example:interface IExample{public void funExample(); //Error: The modifierpublicis not valid for this item.string fun2(string strParam1, string strParam2);//no error}
I need to restrict a class by creating only one object throughout the application. How can I achieve this?
We can declare the constructor of the class as either protected or as private
Can you allow a class to be inherited, but prevent the method from being overridden?
Yes, put 2 modifers before the methodsealed overrideex:class A{public virtual void demo(){}}class B:A{public sealed override void demo(){}}//Class B can be inherited in C, but demo() method cannot be overriden furtherclass C:B{}
What is the purpose of Tuple? Explain with example.
C#4.0 has introduce a new feature call Tuple.It is useful when we want to return more than one value from a method or function.Let us look the below exampleclass Program{static void Main(string[] args){var returnValue = Calculate();string format =Addition: {0}+ Environment.NewLine +Subtraction: {1}+ Environment.NewLine +Multiplication: {2}+ Environment.NewLine +Division: {3};string result = string.Format(format, returnValue.Item1, returnValue.Item2, returnValue.Item3, returnValue.Item4);Console.WriteLine(result);Console.ReadKey(true);}private static Tupleint,int,int,intCalculate(){int num1 = 20;int num2 = 10;return Tuple.Create(num1+num2,num1-num2,num1 * num2,num1/num2);}}As can be seen that using Tuple we can return multiple values from the function/method in a better and readable way.
When we use HTTP handlers can we access session state ?
No, When we use HTTP handlers we cannot access Session state but we can access by using amarkerinterface IRequiresSessionState or IReadOnlySessionState in order to use session state.
Can we declare a class as Protected?
No, a class can not be declared as Protected.A class can be declared with only following access modifiers.AbstractInternalPublicSealedStaticExtern (The extern modifier is used to declare a method that is implemented externally. - http://msdn.microsoft.com/en-us/library/e59b22c5(VS.80).aspx)Thanks
What is Satellite Assembly ?
When we create a Multi-Cultural or Multi-lingual Application and if we want to distribute this application seperately from local modules , the local assemblies that change this core application are said to be Satellite Assemblies .To create the satellite assemblies, We will use Assembly Linker i.e al.exe utility to link the resource file to an assembly.For example :al /t:library /embed:strings.en.resources /culture:en /out:MyAppSrikanth.resources.dllThe /t option ----will direct Assembly Linker to build a library,and the /embed ----option identifies the file to be linked.
What are the access-specifiers available in c#?
Private, Protected, Public, Internal, Protected Internal.
It is not possible for one structure to inherit functionality from another structure or class. True or False ?
NOTE: This is objective type question, Please click question title for correct answer.
Can we create a class private?
No, we can not create a class private, it will give runtime error.Example:private classclassname{}compile time error. class can not be defined as private, protected and internal.
Does Abstract classes contain Constructor?
NOTE: This is objective type question, Please click question title for correct answer.
Can we force Garbage Collector to run ?
Yes we can,It is Possible to force Garbage Collector this can be done by calling a method called Collect().But this makes a performance barrier since this is not a good programming practice.Generally we have no control over garbage collector when it runs.The main work of this GC is it checks if there are any objects which are not used by the application it calls a Destructor which frees the memory allocated to that unused objects.
How will you call non-abstract methods of an abstract class in derived class?
We can call the methods inside the constructor. For eg:public class AbstractTest{public abstract class AbstractClass{public abstract void Method1();public string GetFullname(string lastname, string firstname){return firstname + lastname;}}public class DerivedClass : AbstractClass{public override void Method1(){throw new NotImplementedException();}public DerivedClass(){string fullname = GetFullname(Vijay,Chakraborty);//Do further implementation}}
How is anchoring different from docking?
Docking refers to attaching a control to either an edge(top, right, bottom, or left) or the client area of the parent control. On the other hand, in anchoring you specify the distance that each edge of your control maintains from the edge of the parent control.
Does C# has its own class library ?
C# does not have its own class library. The .NET Framework has a comprehensive class library, which C# can make use of it.
Can we use static notation in indexers in C#?
No.We cant use static notation in indexers.Consider the indexer syntaxpublic int this[int index]{get {// return the value specified by index}set {// set the value specified by index}}Here we can see that indexer uses a reference tothis,Which is not supported by static.The reason behind this is static does not support,instance of a class,so we cant usethisreference.Hence We cant use static notation in indexers.
Which method is used to reads and removes an item from the head of the Queue.
NOTE: This is objective type question, Please click question title for correct answer.
Can we use session variables in a class ?
Yes we can use session variables in class. This can be done using this wayFirst of all we need to import the name spaceUse HttpContext.Current.SessionIn C#.NetHttpContext.Current.Session[Value1] =1;In VB.NetHttpContext.Current.Session(Value1) =1
What are Generics?
Generics means parametrized types. A class, structure, interface, delegates that operates on a parametrized type is called generics.The ability to create type-safe code in which type-mismatch errors are caught at compile time rather than run time is the key advantage of the Generics. So using generics on the class, interface, methods or delegates avoids run time errors as it is caught at the compile time itself.In order to use Generics, we need to work withSystem.Collections.Genericnamespace.IList, IEnumerable, IEnuerator, IComparer, ICollectionand IDictionary are some of the frequently used generics objects.
What are Sealed Classes in C#?
The sealed modifier is used to prevent derivation from a class. A compile-time error occurs if a sealed class is specified as the base class of another class. (A sealed class cannot also be an abstract class)
Why Object Pool is required?
Basically this is a container of objects which reduces the overhead of creating objects each time. This can perform a certain task by allocating an object in the memory pool and can re-use it from memory pool according to the requirement.Whenever the user will request to create an object, the pool manager will perform task for allocating an object from the pool which helps to minimize the memory consumption. This is used to enhance the performance and reduce the load of creation of new objects.
Example for Compile time Polymorphism and Example for Run time Polymorphism?
Example of Compile Time Polymorphism - Method OverloadingExample of Run Time Polymorphism - Method Overriding
Some facts about Virtual methods.
Virtual keyword is used to declare a method inside the base class that can be overridden.Following conditions are applied to a virtual method1. Virtual method can not be declared as Private2. Virtual method can not be declared as Static3. Virtual method may or may not be overridden.4. In order to override the virtual method of the base class, Override keyword is used provided the method signature of the derived class is same as base class, even the access modifier should be same.5. A Virtual method must contain the method body otherwise compiler shall throw error.6. Virtual keyword is only used in base and derived class scenario where you want your method over-ridable in the derived class.Enjoy virtual keyword :)
parameter?
NOTE: This is objective type question, Please click question title for correct answer.
What is the use of stackalloc keyword in C#?
In an unsafe context it is used to allocate C# array directly on the stack.
What is nested class?
A Nested classes are classes within classes.ORA nested class is any class whose declaration occurs within the body of another class or interface.For more details seehttp://www.codeproject.com/KB/cs/nested_csclasses.aspx
By default which class is inherited by a class in C#?
If no class is inhertited, by default a class inherit System.Object.
Why strings are immutable ?
A string is a sequential collection of Unicode characters, which is used to represent text. A String, on the other hand, is a .NET Framework class (System.String) that represents a Unicode string with a sequential collection of System.Char structure.Found this useful, bookmark this page link to the blog or social networking websites.
What is the use of Monitor in C#?
It provides a mechanism that synchronizes access to objects.The Monitor class controls access to objects by granting a lock for an object to a single thread. Object locks provide the ability to restrict access to a block of code, commonly called a critical section. While a thread owns the lock for an object, no other thread can acquire that lock. You can also use Monitor to ensure that no other thread is allowed to access a section of application code being executed by the lock owner, unless the other thread is executing the code using a different locked object.For more visit http://msdn2.microsoft.com/en-us/library/system.threading.monitor.aspx
Why is it not a good programming practice to use empty Destructors ?
If we create a destructor in our class there will be any entry created for the finalize queue.When ever this destructor is called the Garbage Collector is invoked to process that queue.So when ever that destructor is empty it causes a useless loss of performance.
Where we can use DLL made in C#.Net ?
In supporting .Net, we can use DLL made in C#.NET. This is because DLL made in C#.Net is semi compiled version and it is not a com object. It is used only in .Net Framework as it is to be compiled at runtime to byte code.
How can I programmatically list available queues?
TheGetPublicQueuesByLabel,GetPublicQueuesByCategory, andGetPublicQueuesByMachinemethods of theMessageQueueclass provide access to queues on a network.To specify more exactly the type of queue you are looking for, theGetPublicQueuesmethod has aMessageQueueCriteriaparameter in which you can specify combinations of search criteria.
What is an application domain?
An application domain (often AppDomain) is a virtual process that serves to isolate an application. All objects created within the same application scope (in other words, anywhere along the sequence of object activations beginning with the application entry point) are created within the same application domain. Multiple application domains can exist in a single operating system process, making them a lightweight means of application isolation.An OS process provides isolation by having a distinct memory address space. While this is effective, it is also expensive, and does not scale to the numbers required for large web servers. The Common Language Runtime, on the other hand, enforces application isolation by managing the memory use of code running within the application domain. This ensures that it does not access memory outside the boundaries of the domain. It is important to note that only type-safe code can be managed in this way (the runtime cannot guarantee isolation when unsafe code is loaded in an application domain).
What method is used to stop a running thread?
NOTE: This is objective type question, Please click question title for correct answer.
What are the advantages of using Properties in C#.Net?
The advantages of using properties are:• Before allowing a change in data, the properties can validate the data.• Properties can evidently make visible of data on a class from where that data is actually retrieved such as a database.• Properties can also provide events when data is changed, such as raising an event or changing the value of other fields.
Which method is used to add an Item to the end of the Queue?
NOTE: This is objective type question, Please click question title for correct answer.
What is the use of unsafe keyword in C#?
In C# the value can be directly referenced to a variable, so there is no need of pointer. Use of pointer sometime crashes the application. But C# supports pointer, that means we can use pointer in C#.The use of pointer in C# is defined as a unsafe code. So if we want to use pointer in C# the pointer must be present in the body of unsafe declaration. But pointer does not come under garbage collection.Example:-unsafe{int a, *b;a = 25;b =a;Console.WriteLine(b= {0},b);//returns b= 25}
What is optional and named parameter in C#4.0?
Optional parameter allows omitting arguments to function while named parameters allow passing arguments by parameter name.By declaring below variable you are assigning default values to second and third parameter of 2 and 3 respectively (param2 and param3).public void optionalParam(int Param1, int param2 = 2, int param3 = 3);After this you can write,optionalParam(1); //which will be equivalent to optionalParam(1,2,3);Sometimes, you may need to not to pass param2. But, optionalParam(1,"",3) is not valid statement with C#. At this point, named parameter comes to the picture.You can specify arguments like,optionalParam(1, param3:10); //which will be equivalent tooptionalParam(1,2,10);
What is BitArray?
The BitArray collection is a composite of bit values. It stores 1 or 0 where 1 is true and 0 is false. This collection provides an efficient means of storing and retrieving bit values.
How to declare a method in an Interface?
To declare method in an interface, you just need to write the definition of the method like below.void ProcessMyData(int id);string GetMyName(int id);There is no need of writing the modifier as by default all methods in the interface is public.
What will happen if you declare a variable named "checked" with any data type?
Compiler will throw an error as checked is a keyword in C# So It cannot be used as variable name. Checked keyword is used to check the overflow arithmetic checking.
How many types of comments are there in C#?
3 Types of comments1) Single line: //2) MultiLine: /* */3) Xml: /// ///
By default, what is the access specifier of member variables and member function of a class ?
NOTE: This is objective type question, Please click question title for correct answer.
Difference between catch(Exception error) and catch
The code below explains the difference between catch(Exception error) and catchtry{//Code that might generate error}catch(Exception error){//Catches all Cls-complaint exceptions}catch{//Catches all other exception including the Non-Cls complaint exceptions}
What is Queue?
This is a collection that abstracts FIFO (First In First Out) data structure. The initial capacity is 32 elements. It is ideal for messaging components.
What is Asynchronous call and how it can be implemented using delegates?
The Asynchronous calls wait for a method before the program flow is resumed to complete its task. In an asynchronous call, the program flow continues while the method is executes.//create an object for a functionFunction Fun = new Function();//create delegateDelegate Del = new Delegate(Fun.Function);//invoke the method asynchronouslyIAsyncResult call = Delegate.Invoke();
The Items that is put in the Queue is Reads ?
NOTE: This is objective type question, Please click question title for correct answer.
What is C#.NET Generics?
When the C#.NET Generics are instantiated, then the CLR compiles and stores the information related to the generic types that is it refers to the location in memory of the reference type to which it is bound for all the instances. Here the classes and methods can treat the values of different types uniformly.The main purpose of using this is to facilitate type safety, improves performance and reduces code. It also promotes the usage of parameterized types in an application.
Constructor and Destructor
Constructor:-----------------1. The Constructor is the first method that is run when an instance of a type is created. In visual basic a constructor is always Sub new ().2. Constructor are use to initialize class and structure data before use. Constructor never returns a value and can be overridden to provide custom initialization functionality.3. The constructor provides a way to set default values for data or perform other necessary functions before the object available for use.Destructor:---------------Destructors are called just before an object is destroyed and can be used to run clean-up code. You can’t control when a destructor is called.
How can we create an array with non-default value in C#?
Use the Repeat function of Enumerable class.Enumerableclass belongs toSystem.Linqnamespaceint[] b = Enumerable.Repeat(45, 5).ToArray();45: initial value5: number of times the initial value should repeat.foreach (var z in b){Console.WriteLine(z);}
What’s a delegate?
A delegate object encapsulates a reference to a method.
What is MultiCast Delegate ?
A single or uni cast delegate can be instantiated by only a single method . when a Delegatee can make use of more than one method then it is said to be Multicast Delegate.
How to create a strong name?
To create a strong name key use following codeC:\sn -k s.snkStrong name key is used to specify the strong name used to deploy any application in the GAC (Global Assembly Catch) in the system.
What is the difference between DirectCast and CType ?
DirectCast requires the object variable to be the same in both the run-time type and the specified type.If the specified type and the run-time type of the expression are the same, then the run-time performance of DirectCast is better than that of CType.Ctype works fine if there is a valid conversion defined between the expression and the type.
How is the DLL Hell problem solved in .NET?
Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.
what are the properties of datatable?
DataTable is a class that contains data in row column format. Some of the properties of datatable areTableName -- Denotes the name of the DataTable.DataSet -- Gets the dataset for the table.DefaultView -- Gets the view of datatable with RowFilter condition etc.,ROWS -- Get all rows of the table.Column -- Denotes all columns of the tableChildRelation -- Gets the collection of child relations for the data tableParentRelation -- Gets the collection of parent relations for the data tableConstrints -- Gets the collection of constraints maintained by the tablePrimaryKey -- Gets or Sets an array of columns that function as primary key forthe table.Apart from this we have the properties such asExtended Properties, HasErrors, IsInitialized, locale, MinimumCapacity, Prefix, RemotingFormat, Site
You need to create a simple class or structure that contains only value types. You must create the class or structure so that it runs as efficiently as possible. You must be able to pass the class or structure to a procedure without concern that the procedure will modify it. Which of the following should you create?
NOTE: This is objective type question, Please click question title for correct answer.Found this useful, bookmark this page link to the blog or social networking websites.
Can you declare the override method as static while the original method is non-static ?
No, you cannot, the signature of the virtual method must remain the same, only the keywordvirtualis changed to keywordoverride.//Base ClassPublic Class BaseClass{publicvirtualstring Name(){returnmy name;}}//Derived ClassPublic Class DerivedClass: BaseClass{publicoverridestring Name(){returnmy name is Akiii;}}Thanks and RegardsAkiii
Explain the states of a window service application?
a.Running:Normal operation occurs during this stage.b.Paused:The service cannot perform anything beyond till the paused state is changed.c.Stopped:In this, the service will not work until the service is started once again.d.Pending:Running is the stage which comes after Pending. Its like waiting for something to run.
What is an INDEXER in c# ?
Generally in C# Indexers are generally known as Smart Arrays.Defining a c# indexer is almost equal to defining properties.An indexer is a member which enables an object to be indexed in the same way as an array.class IndexerDemo{private string []info = new string[5];public string this [int index]{get{return info[index];}set{info[index] = value;}}}As shown above defining an indexer is much likely defining properties.
Explain with it's usefulness what is Larger Heap Object?
When an object is created, if the object size is greater than 85000 bytes, it will be created in a separate heap called, Large Object Heap. If the size is lesser than 85000 bytes, it will be created in a heap called, Smaller Object Heap.When the Garbage Collector collects the objects, it will perform the compaction on Small Object Heap for more contiguous free memory. However, in case of Large Object Heap, it will not perform any compaction, as it takes more resources to move the Large Objects.
Can we have 2 applications run on a same machine using different Framework Versions ?
NOTE: This is objective type question, Please click question title for correct answer.
Different types of Threading..
The Threading are of 5 types.They are1) Running2) Wait/Sleep/Join3) Abort4) Resume5) SuspendExplanation:If you start a thread by Thread.Start, then the thread will moves to the running state.The Thread in the Running state can move to 3 different states.You can directly move from running state to abort state,by calling Abort method and then finally moving to sleep state.If you want to suspend the thread,then you can call the suspend method and let the thread move to the suspend state and then move to running state by calling Resume method.A thread can go to Wait/Sleep/Join in 3 ways.When the Monitors Wait method is called,then it is the first way.Thread will again go back to Running state when the Pulse method of the Monitor object is called.The second way is by calling the Sleep method,the thread can go in Wait/Sleep/Join state.After the specified millisecond elapses the thread comes back to Running state.The third way is calling the join method. When the join method is called the thread goes in the Wait/Sleep/Join state. Once the other thread finishes this dependent thread is released either to Running or Aborted depending on what kind of logic it is currently running.
Name any two "Permission Classes" generally used while working with CAS ?
1) FileIOPermission2) UIPermission3) SecurityPermission
Can we create constructor for static class?
No, we can not create constructor for static class, as it its member are called by class name itself.Example:using System;using System.Collections.Generic;using System.Linq;using System.Web;///summary/// Summary description for Class1////summarypublic static class Class1{private Class1() //Error: Static classes cannot have instance constructors{//// TODO: Add constructor logic here//}}even static class will have only static members.
Difference between var and dynamic?
var:1)It is a keyword that is used for implicit variable declarationex: var a=100;var b=welcome;The compiler determines the datatype of the variable declared with var keywordon the basis of assigned value. we have to assign value with variable declarationex: var a;a=welcome; This is wrong2)var cannot be used to declare variables at class level.3)var cannot be used as the return type of methods.4)Intoduced in c# 3.0dynamic:1)It is a keyword used for variable declarationex: dynamic a=100;dynamic b;b=good;The datatype of the variable is determined at runtime2)dynamic can also be used to declare class level variablesex: class aa{dynamic d; //correct}3)dynamic can also be used as return type of the methodsexample:class dd{static dynamic pp(){dyanmic d;d=some value;return d;}}4)Introduced in c# 4.0
What is the basic difference between "var" keyword in Javascript and C# ?
In C#, we havedynamickeyword. This dynamic keyword is somewhat similar to javascriptsvar. Here, both create a variable whose type will not be known until runtime, and whose misuse will not be discovered until runtime. C#s var creates a variable whose type is known at compile time.For example:-dynamic dt= new DateTime();dt.bar();//compiles fine but gives an error at runtimeThanks and RegardsAkiii
What is a jagged array?
A jagged array in C# is an array of array.Its a special kind of two dimensional array in which the length of each row is different.Syntaxtype[ ] [ ] array-name = new type[size][ ];Where array-name is the name of the jagged array, and size is the number of rows in that array.Eg:int[][] jaggedArray = new int[2][];jaggedArray[0]=new int[3];jaggedArray[2]=new int[4];Here jagged array contains 2 rows,where the size of first row is 3 and the size of second row is 4.
Which debugging window allows you to see the methods called in the order they were called ?
To view the order of Called method, the only method that is used is Call Stack Window.This window is also useful to see methods called to get to the point at which execution halted.
How to get the default value of the C# variables?
To get the default value of the C# variables,defaultkeyword can be used.float f = default(float);Response.Write(f.ToString());bool b = default(bool);Response.Write(b.ToString());DateTime d = default(DateTime);Response.Write(d.ToString());Thanks
Can we overload static constructors?
No, static constructors are parameterless constructors and so they cannotbe overloaded.Static constructors are called before any other class members are calledand called once only.Their main purpose is to initialize only the static membersof a class.
What is the difference between IEnumerable and IList?
IEnumerableIEnumerableTrepresents a series of items that you can iterate over (using foreach, for example)IEnumerable doesnt have the Count method and you cant access the collection through an index (although if you are using LINQ you can get around this with extension methods).IEnumerable is a general-purpose interface that is used by many classes, such as Array, List and String in order to let someone iterate over a collection. Basically, its what drives the foreach statement.As a rule of thumb you should always return the type thats highest in the object hierarchy that works for the consumers of this method. In your case IEnumerableT.IListIListTis a collection that you can add to or remove from.List has count method and accessed using index.IList is typically how you expose variables of type List to end users. This interface permits random access to the underlying collection.If the consumers of the class need to add elements, access elements by index, remove elements you are better off using an IListT.
Struct can be inherited or not?
No, Struct can not be inherited because it is sealed implicitly.Example:public struct struct1{}public class class1 : struct1 //Error :class1: cannot derive from sealed typestruct1{}
True or False ?
NOTE: This is objective type question, Please click question title for correct answer.Found this useful, bookmark this page link to the blog or social networking websites.
What is Primary Interop Assembly (PIA)?
This is an assembly that contains the type definitions that is metadata of types, which is implemented with COM. This can snatch up multiple versions of the same type library. These are needs to be signed with a strong name by the publisher of the COM type library. This library imported as an assembly when it has been signed.
Is it possible to get the Registry values through C#.net , if so what classes used for it?
With the help of Registry and RegistryKey classes of Microsoft.win32 we can do in .net.We create instance of Registrykey class . Registry is static class , so we can access its method directly.Sample in highlevel:RegistryKey Obj;obj=Register.LocalMachineObject Value=Obj.GetValue(Variable)
What is obsolete method?
Obsolete means old or no longer in use. We can define a method as obsolete using Obsolete keyword/attribute.[Obsolete]public int Fun1(){//Code goes here.}or[Obsolete(Any user define message)] public int Fun1(){//Code goes here..}One thing to note here is O is always capital in Obsolete.
What are anonymous methods?
Anonymous methods are another way to declare delegates with inline code except named methods.Found this useful, bookmark this page link to the blog or social networking websites.
Why C# is called Strongly Typed Language?
C# is called Strongly Typed Language becausen its type rules are very strict. For example you can't called a function that is designed to call Integer with a string or decimal. If you want to do so then you will have to explicitly convert them to integer.
Difference Between String and StringBuilder
String ClassOnce the string object is created, its length and content cannot be modified.SlowerStringBuilderEven after object is created, it can be able to modify length and content.Faster
What’s a multicast delegate?
A delegate that has multiple handlers assigned to it. Each assigned handler (method) is called.
What will be the length of string type variable which is just declared but not assigned any value?
As variable is not initialized and it is of reference type. So it's length will be null and it will throw a run time exception ofSystem.NullReferenceExceptiontype, if used.
What is meant by "Death of Diamond" ?
Every object ina a Class is treated as a diamond. In order to recover the memory associated with this object, if the destruction of a class object after its functionality occurs, then it is known asDeath of Diamond.
How to implement NOT IN clause in LINQ/LAMBDA Query expression?Explain with an example.
This can be done bynegating theContainsextension method. Example follows.Suppose we have a person class as underpublic class Person{public string PersonName { get; set; }public string JobTitle { get; set; }public override string ToString(){returnPerson Name:+ PersonName +JobTitle:+ JobTitle;}}Then populate the Person collection as underprivate static ListPersonPreparePersonCollection(){ListPersonlstPersonCollection = new ListPerson();lstPersonCollection.Add(new Person { PersonName =Amitav Sen, JobTitle =Design Engineer});lstPersonCollection.Add(new Person { PersonName =Bhavini Dey, JobTitle =Software Engineer});lstPersonCollection.Add(new Person { PersonName =Debasis Basu, JobTitle =Software Engineer});lstPersonCollection.Add(new Person { PersonName =Kartik Moin, JobTitle =Lead Engineer});lstPersonCollection.Add(new Person { PersonName =Shahjahan Khan, JobTitle =Technical Lead});return lstPersonCollection;}Suppose we want to get the list of Person who does not has job Title asDesign Engineer,Software Engineer.The complete query will be as underListPersonsource = PreparePersonCollection();string[] strJobTitleToInclude = new string[] {Design Engineer,Software Engineer};//Linq Version(from s in sourcewhere !strJobTitleToInclude.Contains(s.JobTitle)select s).ToList().ForEach(i =Console.WriteLine(i.ToString()));//Lambda Versionsource.Where(i =!strJobTitleToInclude.Contains(i.JobTitle)).ToList().ForEach(i =Console.WriteLine(i.ToString()));OutputPerson Name: Kartik Moin JobTitle:Lead EngineerPerson Name: Shahjahan Khan JobTitle:Technical Lead
Are all methods virtual in C# ?
No. Like C++, methods are non-virtual by default, but those methods can be marked as virtual methods.
Which keyword is used to prevent one class from being inherited by another class in C#
NOTE: This is objective type question, Please click question title for correct answer.
What is type safe object in DotNet that but can be pointed to more than one function at a time and can be invoked explicitly?
NOTE: This is objective type question, Please click question title for correct answer.Found this useful, bookmark this page link to the blog or social networking websites.
How do you directly call a native function exported from a DLL ?
Below is a quick example of the DllImport attribute in action:using System.Runtime.InteropServices;class C{[DllImport(user32.dll)]public static extern int MessageBoxA(int h, string m, string c, int type);public static int Main(){return MessageBoxA(0,Hello World!,Caption, 0);}}This example shows the minimum requirements for declaring a C# method that is implemented in a native DLL. The method C.MessageBoxA() is declared with the static and external modifiers, and has the DllImport attribute, which tells the compiler that the implementation comes from the user32.dll, using the default name of MessageBoxA. For more information, look at the Platform Invoke tutorial in the documentation.
How to declare a property in a class?
int m_PersonID = 0;public int PersonID{get { return m_PersonID; }set { m_PersonID = value; }}
Can “this” be used within a static method?
No ‘This’ cannot be used in a static method. This is because, only static variables/methods can be used in a static method.
You pass a value-type variable into a procedure as an argument. The procedure changes the variable; however, when the procedure returns, the variable has not changed. What happened? (Choose one.)
NOTE: This is objective type question, Please click question title for correct answer.
Which are NOT acceptable ways to open a file for writing?
NOTE: This is objective type question, Please click question title for correct answer.
IS it possible to have different access modifiers on the get/set methods of a property ?
No. The access modifier on a property applies to both its get and set accessors. If you want them to be different, then make the property as read-only (by only providing a get accessor) and create a private/internal set method that is separate from the property.
What is enum?
A enum is nothing but a special value type which specifies a group of named numeric constants.For Example:public enum cube {Length, Height, Width}We can use the enum type ascube len = cube.Length;bool isLength = (len == cube.Length);
If there are many threads updating the same object,then which modifier ensures that the value of the object read by the thread is the latest?
NOTE: This is objective type question, Please click question title for correct answer.
Explain what is Extender provider component? How to use this in the project?
This is a component which provides properties and features to other components or controls. This mechanism is usually used in windows forms applications. The examples of extender provider components are ToolTip, HelpProvider, and ErrorProvider etc.Use an extender provider in your project:• With the help of ProvidePropertyAttribute, you can specify the name of the property that an implementer of IExtenderProvider provides to other controls, attribute to specify the property.• Then use the provided property and try to find which control receives your provided property.• After that use IExtenderProvider, this defines the interface for extending properties to other components.
What is structs?
Structs are similar to a class.Some of the points listed below:• A struct is a value type.• The structs doesn’t support inheritance other than implicitly deriving from object.• A struct can have the members like parameterless constructor, a finalizer, virtual members etc.
What is the difference between == and Equals?
Both are used for comparison of variables, can be overloaded and return a Boolean value.The differences are:-Consider two variables of different types:1) int a = 20;string b =20;//Compiler error (== cannot be applied to int and string)Console.WriteLine(a == b);//output: FalseConsole.WriteLine(a.Equals(b));2)int c = 455;long f = 455;//TrueConsole.WriteLine(c == f);//FalseConsole.WriteLine(c.Equals(f));//Equals strictly checks that 2 variables should be of the same type// == gives True if 2 variablesdata types allow for similar values(Example: int and long)3)Liststringy = new Liststring();y.Add(one);Liststringz = new Liststring();z.Add(one);Console.WriteLine(y == z);Console.WriteLine(y.Equals(z));Both will give False.
What is HashTable?
A Hashtable is a collection of key-value pairs. Entries in this are instance of DictionaryEntry type. It implements IDictionary, ISerilizable, IDeserializable collback interface.
What is Nullable types in c#?
In C# as we know String is reference type and int is value type. A reference type can be assigned with a null value like string s = null; But you can not assign a null value directly to a integer. like int a = null So to make the value type accept a null value, nullable types are used. To make it nullable, a ? is added . in ? a = null;propertiesValue that gets or sets the value. A DateTime? will have a Value of type DateTime, an int? will have one of type int, etc.HasValue that returns true if its not null.You can always convert a value type to a nullable type:Ex: DateTime myDate = DateTime.Now;DateTime? myNullableDate = myDate;
What are Object Initializers?
The Object initializers are the features for programming concepts which was introduced in C#.Net.The aim of using Object Initializers is to intializing the accessible fields or propertiesof an object without the need to write any parameterized constructor or separatestatements.Sample:using System;class Student{int rollno;string stdName;static void Main(){Student s = new Student() { rollno=1,stdName=Ramesh}; //Object Initializer}}
What is Anonymous functions ?
An anonymous function is aninlinestatement or expression that can be used wherever a delegate type is expected. We can use it to initialize a named delegate or pass it instead of a named delegate type as a method parametere.g.In C# 2.0:var output = doSomething(variable, delegate {// Anonymous function code});In C#4.0:var output = doSomething(variable, () ={// Anonymous function code});
How can you rename a file in C#?
Example:if there is a filename known as aa.txt in C drive and we want to change its nameto bb.txt.Use this code snippet:File.Move(c:\\aa.txt,c:\\bb.txt);You must include the namespace System.IO
What are the different ways a method can be overloaded?
Different parameter data types, different number of parameters, different order of parameters.
How do we retrieve day, month and year from the datetime value in C#?
Using the methods Day,Month and Year as followsint day = dobDate.Day;int month = dobDate.Month;int year = dobDate.Year;
Can we inherit a private class into the public class?
No, In C#, a derived class can’t be more accessible than it’s base class. It means that you can't inherit a private class into a public class. So always the base class should be more or equal accessible than a derived class.// Following will throw compilation errorprivate class BaseClass{}public class DerivedClass : BaseClass{}// Following will compile without an errorpublic class BaseClass{}public class DerivedClass : BaseClass{}Hope this helps
What is SortedList?
This is a collection and it is a combination of key/value entries and an ArrayList collection. Where the collection is sorted by key.
Is it possible to debug the classes written in other .Net languages in a C# project ?
It is definitely possible. As everyone knows .net can combine code written in several .net languages into one single assembly. This is also true with debugging.
Explain what are the types of window services?
There are two types of windows services. Those areWin32OwnProcess,Win32ShareProcess.a.Win32OwnProcess:It is a Win32 process that can be started by the Service Controller. This type of Win32 service runs in a process by itself.+b.Win32ShareProcess:It is a Win32 service that allows sharing of processes with other Win32 services.
What is the use of "Default" keyword in C# ?
The default keyword has many usage. One of the uses is it returns a types default value. For reference types it isnulland for value types it iszero.default(Int32) --- prints 0default(Boolean) --- prints falsedefault(String) --- nullThanks and RegardsAkiii
What is operator overloading in C#?
Operator overloading is a concept that enables us to redefine (do a special job) the existing operators so that they can be used on user defined types like classes and structs.For more information visit:http://aspalliance.com/1227_Understanding_Operator_Overloading_in_C.all
What does the term immutable mean?
The data value may not be changed. Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory.Found this useful, bookmark this page link to the blog or social networking websites.
How to declare methods into an Interface
void Calculate();int Insert(string firstName, string lastName, int age);Interface doesn't contain implementation so methods implementation will be written into class inherting this interface.
What is dynamic keyword ?
Its newly introduced keyword of C#4.0. To indicate that all operations will be performed runtime.
Is overriding of a function possible in the same class?
NOTE: This is objective type question, Please click question title for correct answer.
An Interface is a Value type or reference type?
NOTE: This is objective type question, Please click question title for correct answer.
How to sort an array into descending order?
First sort the array using Array.Sort and then use Array.ReverseEg.int[] number = new int[] {6, 4, 7};Array.Sort(number); // sort in ascending orderforeach (int i in number){lblMessage.Text += i +br /;}// reverse ie descending orderArray.Reverse(number);lblMessage.Text +=hr /;foreach (int i in number){lblMessage.Text += i +br /;}
Is it possible to notify application when item is removed from cache ?
Yes.You can useCacheItemRemovedCallbackdelegate defining signature for event handler to call when item is removed from cache.For an example:HttpRuntime.Cache.Insert(CacheItem1, //insert cache item,null,Cache.NoAbsoluteExpiration,new TimeSpan(0, 0, 15),CacheItemPriority.Default,new CacheItemRemovedCallback(RemovalMethod)); //define method which needs to be called when item is removed from cachethe method will be like,private static string RemovedAt = string.Empty;public static void RemovalMethod(String key, object value, //method is declared static so that it can be available when cache item is deletedCacheItemRemovedReason removedReason){RemovedAt =Cache Item Removed at:+ DateTime.Now.ToString(); //Shows the time when cache item was removed}
Types of Errors ?
Configuration ErrorsParser ErrorsCompilation ErrorsRun-Time Errors
What is the difference between a.Equals(b) and a == b?
For value types :“==” and Equals() works same way : Compare two objects by VALUEExample:int i = 5;int k= 5;i == kTruei.Equals(k)TrueFor reference types :both works differently :“==” compares reference – returns true if and only if both references point to the SAME object whileEqualsmethod compares object by VALUE and it will return true if the references refers object which are equivalentExample:StringBuilder sb1 = new StringBuilder(“Mahesh”);StringBuilder sb2 = new StringBuilder(“Mahesh”);sb1 == sb2Falsesb1.Equals(sb2)TrueBut now look at following issue:String s1 = “Mahesh”;String s2 = “Mahesh”;In above case the results will be,s1 == s2Trues1.Equals(s2)TrueString is actually reference type : its a sequence of “Char” and its also immutable but as you saw above, it will behave like Value Types in this case.Exceptions are always there ;)Now another interesting case:int i = 0;byte b = 0;i == bTruei.Equals(b)FalseSo, it means Equals method compare not only value but it compares TYPE also in Value Types.Recommendation :For value types: use “==”For reference types: use Equals method.
How to install and uninstall Windows Services ?
In order to install and uninstall Window Services. First we have to open the command prompt of Visual Studio and we have to move to the project folder where the .exe file is located and then we have to type :For Installing :installutil -i ServiceName.exeFor UnInstalling :installutil -u ServiceName.exe
What is the difference between Dictionary and Hash table?
DictionaryTrying to access an in existent key gives runtime error in Dictionary.Dictionary is a generic typeGeneric collections are a lot faster as theres no boxing/unboxingDictionary public static members are thread safe, but any instance members are not guaranteed to be thread safe.Dictionary is preferred than Hash tableHash tableTrying to access an in existent key gives null instead of error.Hash table is a non-generic typeHash table also have to box/unbox, which may have memory consumption as well as performance penalties.Hash table is thread safe for use by multiple reader threads and a single writing threadThis is an older collection that is obsoleted by the Dictionary collection. Knowing how to use it is critical when maintaining older programs.
What is the purpose of x86, x64 and anycpu platform switch in C# compiler?
When you build any assembly in .Net environment that time you need to used any of these /platform switch or either in Visual Studio pick the platform value inside configuration manager settings./platform:x86- x86 compiles your assembly to be run by the 32-bit, x86-compatible common language runtime./platform:anycpu- anycpu (default) compiles your assembly to run on any platform./platform:anycpu- x64 compiles your assembly to be run by the 64-bit common language runtime on a computer that supports the AMD64 or EM64T instruction set./platform:anycpu- Itanium compiles your assembly to be run by the 64-bit common language runtime on a computer with an Itanium processor.
Write the difference between Group box control and Panel control?
Group Box Control:• A Group box control can be placed with a title.• The group box control cannot display the scroll bar.• Only limited number of controls can be placed within the group box.• Group box is a light weight component.Panel Control:• A panel control can’t be placed with a title.• The panel control can display the scroll bar.• Any number of controls can be placed within the panel.• Panel is a heavy weight component.
What is the use of CommandBehavior.CloseConnection?
We can use pass it with ExecuteReader method of Command object likereader = cmd.ExecuteReader(CommandBehavior.CloseConnection);This will make sure that when we are calling reader.Close() the associated connection object will also be closed.
What is the default modifier for class in C#?
NOTE: This is objective type question, Please click question title for correct answer.
Can multiple catch blocks be executed ?
No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block.
What is Value Types versus Reference Types?
The Value Types which includes most built-in types such as numeric types, char types and bool types as well as the custom struct and enum types. The content of a Value Type variable is simply a value.But in case of Reference Types, it includes all classes, array, interface, and delegate types. This is quite different from value type. It contains two parts that is anobjectand thereferenceto that object. The content of this type is a reference to an object that contains a value.The basic difference between them is, how they are handled inside the memory.
What is the use of static members in C#.NET?
The static members are the members which are not associated with a particular occurrence of any class. To implement this you have to use the keywordstaticbefore any member function. They cant access to non-static members as they are not associated with object instances.
What is the rule for which you can inherit a base class from C# which is being developed in F#?
If a language is CLS-Compilant(Common Language specifications), and also if the class developed by using CLS specifications, then it can be inherited in another CLS-Compilant language.Both F# and C# are CLS-Compilant languages. So, it is possible to inherit the base class in C# where the base class is developed in F#.
What is Finalizer?
These are nothing but class-only methods which will execute before the garbage collector reclaims the memory for an unreferenced object. To implement finalizer, you have prefix the symbol(~) before the name of the class.Syntax:class Sample{~Sample(){…….…….}}
Can we define generics for any class?
No, generics is not supported for the classes which deos not inherits collect class.
What is the difference between WindowsDefaultLocation and WindowsDefaultBounds?
WindowsDefaultLocationmakes the form to start up at a location selected by the operating system, but with internally specified size.WindowsDefaultBoundsdelegates both size and starting position choices to the operating system.
How can you sort the elements of the array in descending order?
By calling Array.Sort() and then Array.Reverse() methods.
If I want to build a shared assembly, does that require the overhead of signing and managing key pairs?
Building a shared assembly does involve working with cryptographic keys. Only the public key is strictly needed when the assembly is being built. Compilers targeting the .NET Framework provide command line options (or use custom attributes) for supplying the public key when building the assembly. It is common to keep a copy of a common public key in a source database and point build scripts to this key. Before the assembly is shipped, the assembly must be fully signed with the corresponding private key. This is done using an SDK tool called SN.exe (Strong Name).Strong name signing does not involve certificates like Authenticode does. There are no third party organizations involved, no fees to pay, and no certificate chains. In addition, the overhead for verifying a strong name is much less than it is for Authenticode. However, strong names do not make any statements about trusting a particular publisher. Strong names allow you to ensure that the contents of a given assembly haven't been tampered with, and that the assembly loaded on your behalf at run time comes from the same publisher as the one you developed against. But it makes no statement about whether you can trust the identity of that publisher.
What is the difference between "Convert" class and "Parse()" method?
The Convert class is used to convert any value from any data type to another data type. This class consist of different methods for making conversions.Example:1) char ch = Convert.ToChar(x); -string to character2) float f = Convert.ToSingle(45); -int to float3) int x = Convert.ToInt(4.5f); -float to intThe Parse method is used to convert only one string value to any other data type. Every data type is consisting of parse() method.Example:1) int x = int.Parse(600); -string to int2) char ch = char.Parse(dnf); -string to character
What is the use of yield keyword in C#?
Yield keyword is used in an iterator block to calculate the value for the enumerator object.An iterator is a method,get accessor, or operator that allows us to use foreach loop on object references of user-defined classes.yield keyword can be used as:1)yield returnexpression;or2)yield break;code snippetusing System;//This namespace provides the IEnumerator interfaceusing System.Collections;public class demo{//GetEnumerator method of IEnumerable interface creates the iteratorpublic IEnumerator GetEnumerator(){for (int i = 1; i=5; i++){yield return i;}}static void Main(){demo t=new demo();//foreach loop calls the GetEnumerator methodforeach (int i in t){Console.WriteLine(i);}}}output:12345
What is Partial Class?
Partial classInstead of defining an entire class, you can split the definition into multiple classes by using the partial keyword. When the application is complied, the C# complier will group all the partial classes together and treat them as a single class. There are a couple of good reasons to use partial classes. Programmers can work on different parts of a class without needing to share the same physical file. Also you can separate your application business logic from the designer-generated code.C#Public partial class Employee{public void DoWork(){}}Public partial class Employee{public void GoToLunch(){}}
Why are there five tracing levels in System.Diagnostics.TraceSwitcher ?
Five levels range from None to Verbose, allows to fine-tune the tracing activities.This is because, the tracing dumps can be quite verbose and for some applications that are constantly running you run the risk of overloading the machine and the hard drive there.
What are the different compiler generated methods when a .NET delegate is compiled?
Compilation of a .NET delegate results in a sealed class with three compiler generated methods whose parameters and return values are dependent on the delegate declaration. The methods are,Invoke()BeginInvoke() andEndInvoke().
Difference between IEnumerable and IEnumerator part-2
In this previous part we have discussed what is IEnumerable and IEnumerator with example.in this Section we will discuss what are the basic diffrence between these two, and when we need to use this.ListstringweekObj = new Liststring();weekObj.Add(Sunday);weekObj.Add(Monday);weekObj.Add(Tuesday);weekObj.Add(Wednesday);weekObj.Add(Thrusday);weekObj.Add(Friday);weekObj.Add(Saturday);Difference:1. IEnumerable actually uses IEnumerator. i.e IEnumerable uses IEnumerator internally through GetIEnumerator.And the SynaExample:IEnumerator weekIterator = weekenum.GetEnumerator();while(weekIterator.MoveNext()){Console.WriteLine(weekIterator.Current.ToString());}2. The biggest difference is states, i.e. IEnumerable does not remember the cursor state i.e currently row which is iterating through, where I enumerator does.# Example 1:Enumerator :public static void EnumeratorDemo(){IEnumerable weekenum = (IEnumerable)weekObj;IEnumerator weekIterator = weekenum.GetEnumerator();DisplayDaysSunToWed(weekIterator);}static void DisplayDaysSunToWed(IEnumerator obj){while (obj.MoveNext()){Console.WriteLine(obj.Current.ToString());if(obj.Current.Equals(Wednesday)){DisplayDaysThrusToRest(obj);}}}static void DisplayDaysThrusToRest(IEnumerator obj){while (obj.MoveNext()){Console.WriteLine(obj.Current.ToString());}}static void Main(string[] args){IEnuDiffrence.EnumeratorDemo();Console.Read();}The above code will return below resultSundayMondayTuesdayWednesdayThrusdayFridaySaturdayContinue in part 3
.NET Framework Interview Questions and Answers
ADO.NET Interview QuestionsAJAX Interview Questions
What is the name used to describe the sending of groups of events captured on the client to the server?
NOTE: This is objective type question, Please click question title for correct answer.
Can we have Secured a secured web page using HTTP protocol instead of HTTPS ?
No we cant, if we really want our asp page to be secured we need to use this HTTPS protocol. The overhead of this is the user must and should type HTTPS in his url otherwise the access will be denied.
What is Lamda Operator? Explain with code.
Lamda expression are concise way to represent an anonymous method that we can use to create delegates or expression tree types. Lambda expression is an inline delegate introduced with C # 3.0 language.static void Main(string[] args){#region Using Lamdaint[] Marks = { 100,54,35,98,62,85,49 };var FailMarks = Marks.Where(Fail =Fail50);foreach (int failMarks in FailMarks)Console.WriteLine(string.Format(Fail Marks are using LAMDA {0}, failMarks));#endregion#region Using Delegatevar delegateFail = Marks.Where(delegate(int x){return (x50);}).ToList();foreach (int failMarks in delegateFail)Console.WriteLine(string.Format(Fail Marks are using DELEGATES {0}, failMarks));#endregion}In the above code I am having integer array of marks ranging from 1-100. I need to print the marks which are lesser then 50 that is Fail. In first part I achieved using Lamda operator by a condition less then 50. In second part I created an anonymous delegate and checking the conditon.The output will beFail Marks are using LAMDA 35Fail Marks are using LAMDA 49Fail Marks are using DELEGATES 35Fail Marks are using DELEGATES 49
What is Parse Error ?
It is just a syntactical error in our ASPX page. It generally happens when our page is unreadable for the part of ASP.NET which transforms our code into an executable code.ExampleDim xmlDoc As New Msxml2.DOMDocument30Dim myErr As IXMLDOMParseErrorxmlDoc.async = FalsexmlDoc.Load App.Path\lyrics.xmlIf (xmlDoc.parseError.errorCode0) ThenDim myErrSet myErr = xmlDoc.parseErrorMsgBox(Error OccuredmyErr.reason)ElseSet myErr = xmlDoc.parseErrorIf (myErr.errorCode0) ThenMsgBox (Error OccuredmyErr.reason)End IfEnd If
Does Private methods also gets inherited in C#?
NOTE: This is objective type question, Please click question title for correct answer.
How can you make your machine shutdown from your program?
Process.Start(shutdown,-s -f -t 0);
What is top-level class?
A top level class is a class that is not a nested class.See what is nested classhttp://www.dotnetfunda.com/interview/exam281-what-is-nested-class.aspx
Difference between String and string in c#?
String:1.String is an class(System.String)2.String is an Reference type(class)string:1.string is an alias name of String class that is created by microsoft2.string is an value type(data type)3.string is a C# keyword4.string is a compiler shortcut for System.String classAs per above points when we use string keyword, it reaches the System.String class and then process accordingly, So we can say that both String and string are same.
Hashtable is a part of which namespace in Dotnet Framework ?
NOTE: This is objective type question, Please click question title for correct answer.
What is the use of var keyword in C#?
This is the new feature in C# 3.0. This enable us to declare a variable whose type is implicitly inferred from the expression used to initialize the variable.eg.var age = 10;Because the initialization value (10) of the variable age is integer type of age will be treated as integer type of variable. There are few limitation of the var type of variables.They are:#. They can't be initialized as null.#. They need to be declared and initialized in the same statement.#. They can't be used as a member of the class.
Can we use goto statement in the finally block?
Yes, we can use the goto statement in the finally block.Code snippet:class abc{static void Main(){try{Console.WriteLine(welcome);}finally{goto dd;dd:Console.WriteLine(last);}}}//This block of code will execute since the label dd is inside the finally block.//if the label dd was outside the finally block, the compiler would have generate//the error--cannot leave the body of finally clause
What is serialization and deserialization? Explain their significance.
While sending an object from a source to destination, an object will be converted into a binary/xml format. This process is calledserialization.After it is reached to destination, it will be converted back to original object. This process is calleddeserialization.Serialization/deserialization will avoid problems like byte reordering,memory layout etc and gives better performance.Byte Reordering :Machines might be of type Big-Endian or Small-Endian. Depends on Endian type, most significant bytes will be stored in left-side or right-side. When an object traverse from One Endian machine to another Endian machine, these bytes needs to be reordered. By serializing/deserializing we are avoiding this.Memory Layout:Different programming languages might store the object in different ways. When the object is traversed,it needs to be stored in memory according to language architecture. By serializing/deserializing we can avoid this problem.
What are Declaration Statements ?
A Declaration Statement declares a Local Variable or Constant Variable .These Statements are allowed in blocks but are not permitted as Embedded Statements.Declaration can be done in this way :declaration-statement:local-variable-declaration ;local-constant-declaration ;
HashTable Class is present inside which of the following NameSpace?
NOTE: This is objective type question, Please click question title for correct answer.
In C# int Refer to?
NOTE: This is objective type question, Please click question title for correct answer.
What does the term immutable mean ?
The data value may not be changed.Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory.
What is difference between throw and throw ex?
When you use throw ex to throw exception, it will update stack trace but in throw it will not update stack trace.Example:Class cls{public static void Main(string[] args){try{function3();Console.WriteLine(Catch Ex); Console.ReadLine();}catch (Exception ex){Console.WriteLine(ex.StackTrace); Console.ReadLine();}}public static void function3(){try{function2();}catch (Exception ex){throw;}}public static void function2(){try{function1();}catch (Exception ex){throw;}}public static void function1(){try{int i = 0;int j = 2 / i;}catch (DivideByZeroException ex){throw;}}}
Can we declare an array variable with var keyword in C# 3.0?
No, var keyword is used to declare implicitly typed local variable. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type.So you can declare a local variable of any type usingvarkeyword but you can't declare an array of variable using var keyword.Correctstring[] str = {ram,sham};foreach (var s in str){Response.Write(s +br /);}Wrongvar[] str = {ram,sham};foreach (var s in str){Response.Write(s +br /);}This will throwCS0246: The type or namespace name 'var' could not be found (are you missing a using directive or an assembly reference?)error.For more info on var keyword seehttp://msdn.microsoft.com/en-us/library/bb383973.aspxThanks
Which of the following statements are false?
NOTE: This is objective type question, Please click question title for correct answer.
Is it possible to restrict the scope of a field/method of a class to the classes in the same namespace ?
No, there is no way to restrict to a namespace.The namespaces are never the units of protection. But if you’re using assemblies, you can use the ‘internal’ access modifier to restrict access to only within the assembly.
How can we sort elements in an array in descending order ?
We have 2 different methods likeArray.Sort()---Which sorts the given arrayArray.Reverse()---Which reverses the arrayWe need to use the Array.Reverse() method after Array.Sort() method is called.Because we get a descending order only if we reverse a sorted array.This can be done using this small example.int[] MyArray = new int[3];MyArray[0] = 98;MyArray[1] = 6;MyArray[2] = 23;Array.Sort(MyArray);Array.Reverse(MyArray);Here we get an output of (98 , 23 , 6). First it sorts the given array and later it reverses which generates our required descending order.
What are three test cases you should do while unit testing?
Positive test casesThis is done with correct data to check for correct output)Negative test casesThis is done with broken or missing data to check for proper handlingException test casesThis is done with exceptions (giving unexpected data or behavior) and check for the exception caught properly or not.
What is virtual function?
To provide a specialized implementation in a class, we can mark the member function name as virtual which can be overridden in the subclasses. We can declare methods, indexers, events, and properties as virtual in a class.It implements the concept of polymorphism. If a class that overrides the virtual method then it has to use the override keyword.
What is the page size in SQL Server?
8 KB --8192you can check this with the query :SELECT low FROM master..spt_values WHERE number = 1 AND type = 'E'
What is Closed constructed type and Open constructed type?
Closed constructed type and open constructed type is term that is used while instantiated an object.For exmapleclass myClassOT{}Class MyClassCint{}In above code class myClassO is the open constructed type as we can pass any type of parameter while instantiating the myClassO object.myClassOinti = new myClassOint(20); // CorrectmyClassOstringi = new myClassOstrubg('my string); // CorrectYou can notice that I can pass either integer or string in the myClassO insntiation as this is the generic class.myClassC is the closed constructed type as I have specified the type of argument to be passed in the myClassC instantiation.myClassCinti = new myClassCint(20); // CorrectmyClassCstringi = new myClassCstrubg('my string); //InCorrect
Can you store multiple datatypes in an Array?
NOTE: This is objective type question, Please click question title for correct answer.
What are the different Debugging tools come with .Net SDK ?
There are 2 different tools they are :DbgcLr: This is also known as Graphic Debugger. Visual studio .Net uses this.CorDBG: This Command line debugger To use this we must compile the original c# file using the /debug switch.
What is the difference between Closing a database connection and Disposing a database connection?And why we must Dispose an external resource like database connection?
We can reopen it later if we close a database connection. But if we Dispose a database connection we cannot use it anymore.We must create a new database object.We must invokeDispose method or Using statementwhenever we have to free external resources. Else we may encounter the below errorAn exception of typeSystem.InvalidOperationExceptionoccurred in System.Data.dll but was not handled in user code Additional information: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identacle object.
An IsolatedStorageFileStream object can be used like any other FileStream object?
NOTE: This is objective type question, Please click question title for correct answer.
Does the finally block execute even when we have unhandled exceptions?
Yes, the finally block executes even if the exception is unhandledConsider this code snippetusing System;class abc{static void Main(){try{Console.WriteLine(enter);int a=Convert.ToInt32(Console.ReadLine());Console.WriteLine(hello+---+a);}finally{Console.WriteLine(good);}}}Compile it and run from the Visual sTUDIO Command promptput some error value (Example: abc)The output will consist of the error message and thegoodstring in thefinally block will be displayed.
Difference between String.Equals(string1,string2) and string1.Equals(string2)
If any of strings value is null, string1.Equals(string2) will throw runtime error butString.Equals(string1,string2) will not throw any error.Example:string str1=null;string str2=abc;str2.Equals(str1); // will give runtime errorString.Equals(str1,str2); //will not give any error
What's the difference between Delegate.Invoke(),Delegate.BeginInvoke(),Control.Invoke(),Control.BeginInvoke()?
Delegate.Invoke:Executes synchronously, on the same thread.Delegate.BeginInvoke:Executes asynchronously, on a threadpool thread.Control.Invoke:Executes on the UI thread, but calling thread waits for completion before continuing.Control.BeginInvoke: Executes on the UI thread, and calling thread doesnt wait for completion.
Which of the following create a FileStream for writing when you want to open an existing file or create a new one if it doesn’t exist?
NOTE: This is objective type question, Please click question title for correct answer.Found this useful, bookmark this page link to the blog or social networking websites.
How can you prevent the class from being inherited by other classes without using "Sealed" keyword.?
By declaring base class constructor as Private we can avoid that class being inherited by another class. When we create the object for the derived class the base class constructor called automatically and executed. Hereit cannot be executed due to its protection level. See the code snippet:namespace Example{class Base{private Base(){}public void Test(){Console.WriteLine(Test);}}class Program : Base{static void Main(string[] args){Program pObj = new Program();pObj.Test();}}}If we run the above code we get the following error :Example.Base.Base()is inaccessible due to its protection level
How and why to use Using statement in C#?
Using statement is used to work with an object in C# that inherits IDisposable interface.IDisposable interface has one public method called Dispose that is used to dispose off the object. When we use Using statement, we don't need to explicitly dispose the object in the code, the using statement takes care of it. For eg.Using (SqlConnection conn = new SqlConnection()){}When we use above block, internally the code is generated like thisSqlConnection conn = new SqlConnection()try{}finally{// calls the dispose method of the conn object}Using statement make the code more readable and compact.For more details readhttp://www.codeproject.com/KB/cs/tinguusingstatement.aspx
What debugging tools come with the .NET Framework SDK?
CorDBG – command-line debuggerThe Runtime Debugger helps tools vendors and application developers find and fix bugs in programs that target the .NET Framework common language runtime. This tool uses the runtime Debug API to provide debugging services. Developers can examine the code to learn how to use the debugging services. Currently, you can only use Cordbg.exe to debug managed code; there is no support for debugging unmanaged code. To use CorDbg, you must compile the original C# file using the /debug switch.Click for more detailshttp://msdn.microsoft.com/en-us/library/a6zb7c8d(VS.80).aspxDbgCLR – graphic debugger.The Microsoft CLR Debugger (DbgCLR.exe) provides debugging services with a graphical interface to help application developers find and fix bugs in programs that target the common language runtime. The CLR Debugger, and the accompanying documentation, is based on work being done for the Microsoft Visual Studio 2005 Debugger. As a result, the documentation refers mostly to the Visual Studio Debugger, rather than the CLR Debugger. In most cases, the information is applicable to both debuggers. However, you will find sections of the documentation describing some features that are not implemented in the CLR Debugger (see the next paragraph). You can simply ignore these features and sections.Here are some of the main differences between the CLR Debugger and the Visual Studio Debugger as described in the documentation:* The CLR Debugger does not support the debugging of Win32 native code applications. Only applications written and compiled for the common language runtime can be debugged with the CLR Debugger.* Remote debugging is not implemented in the CLR Debugger.* The Registers window is implemented in the CLR Debugger, but no register information appears in the window. Other operations that involve registers or pseudoregisters, such as displaying or changing a register value, are not supported. For more information see, How to: Use the Registers Window.* The Disassembly window is implemented in the CLR Debugger but shows the disassembly code that would be generated for the application if it were compiled as Win32 native code rather than common language runtime code. For more information see, How to: Use the Disassembly Window.* The CLR Debugger does not support F1 help.* The CLR Debugger does not support the Autos window feature.Click for more detailshttp://msdn.microsoft.com/en-us/library/7zxbks7z(VS.80).aspx
Can we Inherit the class defined with private constructor?
No, we can not inherit the class defined with private constructor.public class A:B{}public class B{private B(){}}Here if we will compile this code error will come:Namespace.B.B() is inaccessible due to its protection level
What is private constructor? What is the use of it?
Private constrors are the special kind of constructor, which are allowed to not set create instace of a class from outside of the class. They are basically created when a class only have static members.when you want to craete a single instance of class than use private constructor, basically they are used for Singlton pattern also.
why can you prove that string is immutable datatype while StringBuilder is Mutable Datatype ?
Hi AllWe can prove this by using Object.GetHashCode () Method provided in super class of all .net langues..The hash code is a numeric value that is used to identify an object..Please refer the below line of code..using System;using System.Text;class Program{static void Main(string[] args){string strtemp =Prad;Console.WriteLine(strtemp ++ strtemp.GetHashCode());strtemp = strtemp +eep;Console.WriteLine(strtemp ++strtemp.GetHashCode());StringBuilder sb = new StringBuilder(Prad);Console.WriteLine(sb ++ sb.GetHashCode());sb.Append(eep);Console.WriteLine(sb ++ sb.GetHashCode());}}/*outputPrad 432992021Pradeep -673750172Prad 46104728Pradeep 46104728 */As we can see for any operation performed on the string the new memory is created that y it is called immutable..while for stringbuilder for all the operation the same memory is being modified.. as we can see the hashcode both time is same.Happy coding :-)
What is CLS-Compliant?
CLSCompliant attribute on an assembly (or a program element) and have the compiler check if your code is CLS (Common Language System) compliant. This means it works properly when consumed by other .NET languages.
If there is no valid conversion between two types, what should you do when implementing the IConvertible interface?
NOTE: This is objective type question, Please click question title for correct answer.
Can we make a class private in namespace?
No we can not create a class private in namespace. because namespace elements can not be private, protected or protected internal.If you will create it, compiler will trow compile time error.Example:namespace TestNamespace{private class testClass{}}comiple time error:Elements defined in a namespace cannot be explicitly declared as private, protected, or protected internal
What is Scavenging in .NET?
When we implement the Caching concept in the application,all the cached items will be stored in the memory.When executing the application if memory resources are low,then all the cached items stored in the memory get remove from the caching.this concept is calledScavenging.
What is the correct order for Catch clauses when handling different exception types?
NOTE: This is objective type question, Please click question title for correct answer.
What is boxing and unboxing in C#.NET? Explain briefly with sample code.
Boxing is a process of converting value type variable to reference type or object type. The boxing can be done implicitly or explicitly.Implicit boxing means the type casting or conversion can be done automatically where as explicitly can be done by manual type casting.Unboxing is an explicit conversion from reference type to a value type. It has to be done explicitly.Please look at the following example:static void Main(string[] args){#region Boxingint intVariable = 10;object objImplicitBoxing = intVariable; //Implicit Boxingobject objExplicitBoxing = (object)intVariable; //Explicit BoxingConsole.WriteLine(string.Format(Implicit Boxing {0},objImplicitBoxing));Console.WriteLine(string.Format(Explicit Boxing {0},objExplicitBoxing));#endregion#region Unboxingint iUnbox = (int)objImplicitBoxing; //Explicit UnboxingConsole.WriteLine(string.Format(Explicit Unboxing {0},iUnbox));#endregion}From the above code:object objImplicitBoxing = intVariable;The above line indicates assigining the integer value to object DIRECTLY.object objExplicitBoxing = (object)intVariable;The above line type casts the integer value to object and assigning to another object.int iUnbox = (int)objImplicitBoxing;The above line type casts the object to Integer value and assigning to Integer variable.
Write a code snippet for swapping two variables without using third variable..
For Integersint i = 10;int j = 15;i = i + j;j = i - j;i = i - j;Console.WriteLine(The swapped values are i={0},j={1}, i, j);In the above code I am adding the two variables. Here i+j = 25 and assigning to i. Now I am subtracting j from i which is 25-15 is equals 10 and assigning to j. In third line I am subtracting j (currently it is 10) from i and assigning to i. So here 25-10=15. At last we will be having the values swapped i=15 and j=10.For String:--------------I used replace function here. If any one has better solution then this please let me know.string a =Naga;string b =Sundar;a = a + b;b = a.Replace(b,);a = a.Replace(b,);Console.WriteLine(The swapped values are a={0},b={1}, a, b);I am using the same logic that I used for Integers. I am appending stringaandband saving it ina. Now the variableacontains textNagasundar. From here I am using replace function and eliminatesSundar. Now stringbcontainsNaga. Once again I am using replace function so that I am removing stringb(currentlyNaga) froma. So I am gettingSundarin variableaandNagain variableb
How you create partial methods?
To create a partial method we have to declare two parts that is definition or we can say declaration and the implementation. Here the implementation is optional i.e. when it is not declared then all calls to the method are removed at compile time. So that the code in partial class can freely use partial method even if implementation is not provided. If implementation is not declared then the compiler will define the declaration and will call to the methods.Following points to keep when creating partial methods…• The declaration of Partial method must begin with a partial keyword.• The return type of a partial method must be void.• Partial methods can have ref parameters but not the out parameters.• The default type of Partial method is private, and it cannot be virtual.• Partial methods cannot be extern, because it determines whether they are defining or implementing.
What happens if you inherit multiple interfaces and they have conflicting method names?
It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you’re okay.To Do: Investigate
Which namespace is required to use Generic List?
NOTE: This is objective type question, Please click question title for correct answer.
What is Delegates?
A delegate in C# allows you to pass method of one class to objects of other class that can call these methods.ORA delegate is an object that holds the reference to a method.In C++ it is called function pointer.
Which of the following are types of changes that can be detected by the File-SystemWatcher?
NOTE: This is objective type question, Please click question title for correct answer.
what is immutable and mutable?
Strings are immutable. What this means is application is that modifying a string creates new string data on the heap and modifies the pointer on the stack to point to the new location. The data on the heap that is not referenced from the stack will be cleared at garbage collection time, but until then it’s wasteful.In comparison,StringBuilders are mutable. Modifications/additions to the stringbuilder will update the data in the heap instead of making copies of it each time.(StringBuilder sb = new StringBuilder; sb.Add(“test”); sb.Add(” and test2?);That code will create a pointer on the stack and a data value on the heap, update that data value to add the second string and that’s it. Doing the same with strings would have left an abandoned string data value on the heap of value “test” waiting on the GC.
Difference between Type.GetType() and Object.GetType()
Both methods are used for extracting datatype related information and are defined in Typeand Object classes.Type.GetType() does not need a variable or object reference .It can be directly used.example:DataTable dt = new DataTable();dt.Columns.Add(eno, Type.GetType(System.Int32));dt.Columns.Add(ename, Type.GetType(System.String));Object.GetType(): needs a variable or an object reference,example:int a=30;//int is indirectly derived from the Object class.Console.WriteLine(a.GetType().Name);
What is the difference between console and window application?
A console application is designed to run at the command line with no user interface.A Windows application,which has a user interface, is designed to run on a user’s desktop.
Can we define two main methods in an application ?
NOTE: This is objective type question, Please click question title for correct answer.
Write a lambda expression to add all the natural numbers below five hundred that are multiples of 7 or 11.
var ans = Enumerable.Range(0, 500).Where(i =i % 7 == 0 || i % 11 == 0).Sum();Enumerable.Range generates a sequence of integral numbers within a specified range.In this case it is between 0 to 500. After that inside the Where extension method we are checking if the number is divisible by 7 as well as 11 or not.Which ever number satisfies the condition, we are taking a sum of that.Result: 27660
What is constructor chaining?
Constructor Chaining is used to call a constructor in another constructor. Means you can initialize some fields using another constructor in one constructor.Example:Public class Example{string strName;string strCity;public Example(string Name, string City){this.strName = FirstName;this.strCity = City;}//another constructorpublic Example(string Name):this(Name,Delhi){this.strName= FName;}}
What is Microsoft Intermediate Language (MSIL)?
A .NET programming language (C#, VB.NET, J# etc.) does not compile into executable code; instead it compiles into an intermediate code called Microsoft Intermediate Language (MSIL). As a programmer one need not worry about the syntax of MSIL - since our source code in automatically converted to MSIL. The MSIL code is then send to the CLR (Common Language Runtime) that converts the code to machine language, which is, then run on the host machine. MSIL is similar to Java Byte code.MSIL is the CPU-independent instruction set into which .NET Framework programs are compiled. It contains instructions for loading, storing, initializing, and calling methods on objects.Combined with metadata and the common type system, MSIL allows for true cross- language integration Prior to execution, MSIL is converted to machine code. It is not interpreted.
What’s the difference between System.String and System.Text.StringBuilder classes?
System.String is immutable. System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.
Which enumeration defines different PenCap in C#?
LineCap enumeration which defines different pen cap styles as follows,public enum LineCap{Flat, Square, Round, Triangle, NoAncher, SquareAnchor,RoundAnchor, DiamondAnchor, ArrowAnchor, AnchorMask, Custom}
Difference between catch(Exception objex) and catch() block
catch(Exception objEx) will catch only .net compliance exceptions and catch() will catch all types of exception non-compliance and .net compliance.
What types of data can a GZipStream compress?
NOTE: This is objective type question, Please click question title for correct answer.
Can you pass value types by reference to a method?
Yes, you can pass value types by reference to a method. Below is one sample code snippet to have clear idea.using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Sample{class Program{public static void Main(){int a = 10;Console.WriteLine(Value of a before passing to the method =+ a);Function(ref a);Console.WriteLine(Value of a after passing to the method by reference=+ a);}public static void Function(ref int Num){Num = Num + 5;}}}
Difference between classes and structures?
A struct is a value type and a class is a reference type.When we instantiate a class, memory will be allocated on the heap and when struct gets initiated it gets memory on the stack.Classes can have explicit parameter less constructors. But structs dosn't have this.Classes support inheritance. No inheritance for structs.A struct cannot inherit from another struct or class, and it cannot be the base of a class. Like classes, structures can implement interfaces.
What do you mean by virtual property? Give an example?
A property declared with virtual keyword is considered as virtual property. These enables derived classes to override the property behavior by using the override keyword. In the output you can see the over riden implementation. A property overriding a virtual property can also be sealed, specifying that for derived classes it is no longer virtual.using System;using System.Collections.Generic;using System.Linq;using System.Text;class Employee{private string fName = string.Empty;Private string lName = string.Empty;public string FirstName{get{return fName;}set{fName = value;}}public string LastName{get{return lName;}set{lName = value;}}// Here take FullName is as a virtualpublic virtual string FullName{get{return fName +,+ lName;}}}class Company : Employee{// Overiding the FullName virtual property derived from employee classPublic override string FullName{get{returnMr.+ FirstName ++ LastName;}}}class Main{public static void Main(){Company CompanyObj = new Company();CompanyObj.FirstName =Satish;CompanyObj.LastName =Reddy;Console.WriteLine(Employee Full Name is :+ CompanyObj.FullName);}}
Can we declare abstract keyword on fields in a class ?
No we cannot.For example :-public abstract class clsbase{public abstract string str =Akiii;}executing the code will results in the following error :-Error 1 The modifierabstractis not valid on fields. Try using a property instead.Thanks and RegardsAkiii
Write a way to read an image from a path to a bitmap object
We can directly read an image file and load it into a Bitmap object as below.Bitmap myBmpObj = Bitmap.FromFile(strPath);We can also set Image path during the Initilization of Bitmap Object. Code as given below.Bitmap loBMP = new Bitmap(strPath);Modified By:Moderator3
How do I simulate optional parameters to COM calls ?
To simulate optional parameters to COM calls, You must use the Missing class and pass Missing.Value (in System.Reflection) for any values that have optional parameters.
What is the difference between proc. sent BY VAL and BY SUB ?
The main difference between these two is mentioned below:BY VAL: The changes that are made will not be reflected back to the variable.By REF: The changes will be reflected back to that variable.( same assymbol in c, c++)
By which method we can get the version of installed .Net Framework?
NOTE: This is objective type question, Please click question title for correct answer.Found this useful, bookmark this page link to the blog or social networking websites.
Difference between Abstract class and interface?
1.Through the abstract class we cannot achieve the multiple inheritance in c-sharp. while by interface we can.2. We can declare the access modifier in abstract class but not in interface. Because by default everything in interface is public
Write a linq query to find the N-th highest salary of employee. Also the query shoudl be able to handle the Tie situation i.e. the program has to return a collection when multiple employees have equal salary.
Let us first make the environment.First let us declare an Employee classclass Employee{public string EmpName { get; set; }public int Salary { get; set; }}Then populate some records to itprivate static ListEmployeeGetEmpRecord(){ListEmployeeempCollection = new ListEmployee();empCollection.Add(new Employee { EmpName =Emp1, Salary = 10000 });empCollection.Add(new Employee { EmpName =Emp2, Salary = 3456 });empCollection.Add(new Employee { EmpName =Emp3, Salary = 14256 });empCollection.Add(new Employee { EmpName =Emp4, Salary = 15000 });empCollection.Add(new Employee { EmpName =Emp5, Salary = 10000 });empCollection.Add(new Employee { EmpName =Emp6, Salary = 6000 });empCollection.Add(new Employee { EmpName =Emp7, Salary = 2000 });empCollection.Add(new Employee { EmpName =Emp8, Salary = 5000 });empCollection.Add(new Employee { EmpName =Emp9, Salary = 7000 });empCollection.Add(new Employee { EmpName =Emp10, Salary = 7000 });return empCollection;}Finally let us write the programvar empCollection = GetEmpRecord();int whichEmpSalary = 3;var employees = (from emp in empCollectiongroup emp by emp.Salary into gorderby g.Key descendingselect new{EmpRecord = g.ToList()}).ToList();employees[whichEmpSalary - 1].EmpRecord.ForEach(i =Console.WriteLine(Emp Name {0} earns {1}, i.EmpName, i.Salary));Console.ReadKey();Let us analyze the program. First we are grouping up the Employee Record Set by their salary.If we put a break point there and check , we will find that there are a total of 8 elements since both Emp1 and Emp5 are earning 10000 while Emp9 and Emp10 are earning 7000 each.But it is not sorted. In order to sort the record set, we have introduce the order by clause that will guaranteed to bring the result in a sorted order.Finally we are projecting the record using the select statement.At this stage we will get the count as 8 only but with sorted record set.Suppose we want to find out the third highest salary which should beEmp1andEmp5(both earning 10000 each). The first will beEmp4with 15000 and second isEmp3with Salary = 14256.Since it is a collection, we can use index as shown under to obtain the desired result.var result = employees[2];will give the desire result.OutputEmp Name Emp1 earns 10000Emp Name Emp5 earns 10000//Lambda versionempCollection.GroupBy(g=g.Salary).OrderByDescending(o=o.Key).Select(s=new{EmpRecord = s.ToList()}).ToList()[whichEmpSalary - 1].EmpRecord.ForEach(i =Console.WriteLine(Emp Name {0} earns {1}, i.EmpName, i.Salary));
Difference between IEnumerable and IEnumerator Part 1
Before Going for the difference between IEnumerable and IEnumerator , let first discuss what is IEnumerable and IEnumerator is with example. I am going to use the below listListlt;stringgt; weekObj = new Listlt;stringgt; ();weekObj.Add(Sunday);weekObj.Add(Monday);weekObj.Add(Tuesday);weekObj.Add(Wednesday);weekObj.Add(Thrusday);weekObj.Add(Friday);weekObj.Add(Saturday);IEnumerableThe IEnumerable interface is a generic interface that provides an abstraction for looping over elements.In addition to providing foreach support, it allows you to tap into the useful extension methods in the System.Linq namespace, opening up a lot of advanced functionalityThe IEnumerable interface contains an abstract member function called GetEnumerator() and return an interface IEnumerator on any success call.Example: Traversing IEnumerableIEnumerable weekenum = (IEnumerable)weekObj;foreach (string day in weekenum){Console.WriteLine(day);}IEnumeratorIEnumerator provides two abstract methods and a property to pull a particular element in a collection. And they are Reset(), MoveNext() and Current The signature of IEnumerator members is as follows:void Reset() : Sets the enumerator to its initial position, which is before the first element in the collection.bool MoveNext() : Advances the enumerator to the next element of the collection.object Current : Gets the current element in the collection.Example : Traversing IEnumeratorIEnumerator weekIterator = weekObj.GetEnumerator();if (weekIterator.MoveNext()){Console.WriteLine(weekIterator.Current.ToString());}Continue with part 2
Tell me one reason for dotnet doesn't have multiple inheritance
To avoid ambiguity and deadlocks
Can we inherit Multiple Interfaces into an Interface ?
NOTE: This is objective type question, Please click question title for correct answer.
How to explicitly implement the interface method?
To explicitly implement interface we need to prefix the method name with the name of the interface following by .(dot).string IInterface1.HelloNet(){returnInterface 1 : Hello NET;}Assuming that HelloNet method is in IInterface1 as well as another interface that is inherited in the class.
Can you have different access modifiers on the get/set methods of a property in C#?
No. it's not possible. The access specifier has to be same for get and set.
What is Co-Variance and Contra Variance in C#4.0? Explain with example
Converting from a broader type to a specific type is called co-variance.If B is derived from A and B relates to A, then we can assign A to B. Like A=B. This is Covariance.Converting from a more specific type to a broader type is called contra-variance. If B is derived from A and B relates to A, then we can assign B to A. Like B= A. This is Contravariance.Co-variance and contra-variance is possible only with reference types; value types are invariant.Co-variance is guaranteed to work without any loss of information during conversion. So, most languages also provide facility for implicit conversion. Contra-variance on the other hand is not guaranteed to work without loss of data. As such an explicit cast is required. Though, both are type-safe and will compile perfectly and run. e.g. Assuming dog and cat inherits from animal, when you convert from animal type to dog or cat, it is called co-variance. Converting from cat or dog to animal is called contra-variance, because not all features (properties/methods) of cat or dog is present in animal.In .NET 4.0, the support for co-variance and contra-variance has been extended to generic types. No now you can apply co-variance and contra-variance to Lists etc. (e.g. IEnumerable etc.) that implement a common interface. This was not possible with .NET versions 3.5 and earlier.class Fruit { }class Mango : Fruit { }class Program{delegate T Funcout T();delegate void Actionin T(T a);static void Main(string[] args){// CovarianceFuncMangomango = () =new Mango();FuncFruitfruit = mango;// ContravarianceActionFruitfr = (frt) ={ Console.WriteLine(frt); };ActionMangoman = fr;}}
What does the parameter Initial Catalog define inside Connection String ?
The parameter Initial Catalog inside the Connection String defines the database name to connect to.
How do we check Array out of range error in C#
In C# we have IndexOutOfRange exception which is used to check the index out of range exception.Example:try{------}catch(IndexOutOfRangeException ex){Console.WriteLine(An index was out of range!);}catch(Exception ex){Console.WriteLine(Error occured:+ ex.Message);}
How can we underline a particular character in the Text of the Window Label
example: if we want to write Hello on a Label and underline theHcharacter,1) TypeHello in the text property2) Set UseMnemonic property of the Label to true(It is true by default)
Write the syntax of foreach loop with hashtable and get the key, value pair from the hashtable?
HashTable ht = new HashTable();ht.Add(1,A);ht.Add(2,B);ht.Add(3,C);foreach(DictionaryEntry de in ht){Console.WriteLine(string.Format(Key : {0} Value: {1}, de.Key.ToString(),de.Value.ToString()));}
What is lock statement in C#?
Lock ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread attempts to enter a locked code, it will wait, block, until the object is released.
What is the use of ?? operator in C#?
This operator allows you to assign a value to a nullable type if the retrieved value is in fact null.
How can we make a browser window opening with a maximum size on a button click?
We can make that by setting an attribute FullScreen =Yesby this wayButton1.Attributes.Add(onclick,window.open(’page2.aspx’,’’,’fullscreen=yes’));
How can prevent a class to be inherited?
Using sealed keyword with class. you can use sealed class using object but can not inherit any class from a sealed class.Example:sealed class exampleSealed{//code of a class.}class derived : exampleSealed{ //error can not inherit from exampleSealed}
Write a C# sharp Program to check wheather the given string is Palindrome or not. (Ex: LEVEL is palindrome).Don't use inbuild string functions.
PALINDROME string is sequence of letters that is the same forward as backward. Example is LEVEL.class Program{public bool IsPalindrome(string sInput){int iLengthofInput = 0;//Find Length of the string.foreach(char chr in sInput)iLengthofInput++;char[] sArrReverse = new char[iLengthofInput];int iIncr =iLengthofInput-1;foreach(char chr in sInput){sArrReverse[iIncr] = chr;iIncr--;}string sRevString = new string(sArrReverse);#region AnotherWay for string initializng//string sRevString =;//for(int i = 0; iiLengthofInput; i++)//{// sRevString += sArrReverse;//}#endregionif (sRevString == sInput)return true;elsereturn false;}static void Main(string[] args){Program pObj = new Program();Console.WriteLine(pObj.IsPalindrome(LEVEL);Console.Read();}}In the above code I am finding the length of the string. For example : LEVEL - length is 5.char[] sArrReverse = new char[iLengthofInput];int iIncr =iLengthofInput-1;foreach(char chr in sInput){sArrReverse[iIncr] = chr;iIncr--;}In the above code I am creating the arrary calledsArrReverseand initializing with length of input string.In Foreach loop I am assigning values of input string in reverse order. So now sArrReverse containsLEVELwhich is reverse form of original input stringLEVEL.I am creating a stringsRevStringand initializing withsArrReversevalue in the following codestring sRevString = new string(sArrReverse);ORstring sRevString =;for(int i = 0; iiLengthofInput; i++){sRevString += sArrReverse;}Using If condition I am checking both strings and returning the value depends on condition.
Which one of the following language is not included in the installation of .net Framework ? (Default Installation)
NOTE: This is objective type question, Please click question title for correct answer.
Yes or No
No.InMethod Overriding, the signature of the method cannot change. Everything must remains same only the implementation in the derived class will differ.Thanks and RegardsAkiii
Can we assign values to read only variables?if yes then how?
yes, we can assign values to read only variables either at a time of declaration or in constructorsFound this useful, bookmark this page link to the blog or social networking websites.
Can we declare event and delegates in an interface ?
No,we cannot declare delegates in interface however we can declare events in interface.So interface can only contains the signature of the following membersMethodsPropertiesIndexersEvents
Is it possible to instantiate a struct without using a new operator and can a struct inherit from another struct or class in C#?
Yes, it is possible to instantiate a struct without using a new operator.No, a struct cannot inherit from another struct or class, and it cannot be the base of a class.
A class has field with value initialized and this field value has also been set into constructor. Which value is set first initialized value or constructor value?
NOTE: This is objective type question, Please click question title for correct answer.
When we have one single try statement and multiple catch blocks can these multiple catch blocks be executed ?
NOTE: This is objective type question, Please click question title for correct answer.Found this useful, bookmark this page link to the blog or social networking websites.
What is the difference between ref & out parameters?
An argument passed to a ref parameter must first be initialized.When compared this to an out parameter, whose argument does not have to be explicitly initialized before being passed to an out parameter.
Which of these variables are compiled as an anonymous type?
NOTE: This is objective type question, Please click question title for correct answer.Found this useful, bookmark this page link to the blog or social networking websites.
Which Object contains all the properties and methods for every Asp.net page ?
NOTE: This is objective type question, Please click question title for correct answer.
What is the CIL representation of implicit and explicit keywords in C#?
The CIL representation is op_Implicit and op_Explicit respectively.
Difference between static variable and constant in c#?
Static Variable:1.Variable set at run time2.Can be assigned for reference types.3.Initialized on constructorsConstant:1.Variable set at compile time itself.2.Assigned for value types only3.must be initialized at declaration time4.only primitive data types.
what is the use of virtual and override keywords?
When you override any function or any function is overridable then apply virtual keyword with that function in base class and in derived class add override keyword with that function.Example:Class parent{public virtual void fun_overridable(){//some code here}}class child:parent{public override void fun_overridable(){//some code here}}
Which of the following is a value type in C# ?
NOTE: This is objective type question, Please click question title for correct answer.
What is Jump Constructs?
The break statement causes an immediate exit from the for, switch, while statements.example:for(count=0;count20;count++){if(count==10){break;}}
What is an ArrayList?
ArrayList is a dynamic array. Elements can be added&removed from an arraylist at the runtime. In this elements are not automatically sorted.
reference?
public bool GetValue(refint returnValue );This will pass the numeric by reference.You can modify the value ofreturnValue within the body ofGetValueand it will persist when the methodcall returns.
What is Jagged Array?
An array whose elements are arrays is known as a jagged array.The elements of this jagged array can be of different dimensions and sizes.A jagged array is sometimes called as an array–of–arrays.
What is Regular Expressions in C#.NET?
The Regular Expressions are the languages which identifies character patterns. Basically this is used for the following tasks such as:• To validate the text input such as passwords, numbers etc.• Parsing the textual data into more structured forms. For example, extracting data from an HTML page to store in database.• Replacing the pattern of text into a document.All Regular Expression types are defined inSystem.Text.RegularExpressions.
How to load assembly from GAC?
Lets say you have to load the assembly from GAC on button click event then you should write following method.protected void btn_Click(object sender, EventArgs e){AssemblyName asm = new AssemblyName(ClassLibrary1, Version=1.1.0.0, Culture=neutral,PublicKeyToken=fbc28d9ca2fc8db5);Assembly al = Assembly.Load(asm);Type t = al.GetType(ClassLibrary1.Class1);MethodInfo m = t.GetMethod(Method1);str =reflection -+ (string)m.Invoke(null, null);MessageBox.Show(str);}For more visit http://www.infosysblogs.com/microsoft/2007/04/loading_multiple_versions_of_s.html
Explain about abstract property. Give an example?
A property with abstract keyword is considered as abstract property. An abstract property cannot have any implementation in the class. In derived classes you must have to write their own implementation.using System;using System.Collections.Generic;using System.Linq;using System.Text;abstract class Employee{private string fName = string.Empty;private string lName = string.Empty;public string FirstName{get{return fName;}set{fName = value;}}public string LastName{get{return lName;}set{lName = value;}}}// FullName is abstractpublic abstract string FullName{get;}}class Company: Employee{// Overiding the FullName abstract property derived from employee classpublic override string FullName{get{returnMr.+ FirstName ++ LastName;}}}class Main{public static void Main(){Company CompanyObj = new Company();CompanyObj.FirstName =Satish;CompanyObj.LastName =Reddy;Console.WriteLine(Employee Full Name is :+ CompanyObj.FullName);}}
What is garbage collection?
Garbage collection is a mechanism that allows the computer to detect when an object can no longer be accessed. It then automatically releases the memory used by that object (as well as calling a clean-up routine, called afinalizer,which is written by the user). Some garbage collectors, like the one used by .NET, compact memory and therefore decrease your program's working set.
What is a Constructor?
A constructor is a special method for initializing a new instance of a class.The constructor method for a class will have the same name as that of a class.A class may have multiple constructors in which, each constructor will have the same name, but will have different arguments.There is no need of calling a constructor, It will evoke automatically when an Object of the class is created.
Which class defines different events for controls in C#?
TheControlclass defines a number of events that are common to many controls.
Can DateTime be assigned null ?
Yes we can assign null to a variable of DateTime datatypeFor ex :.Consider this snippetclass A{static void Main(){DateTime? a=null;Console.WriteLine(value+---+a);}}//Compile it and execute://Explanation://DateTime is a nullable data type(it is a value type) whose variable can be assigned null values when declared with ? sign.In the output, we shall see the string value concatenated with blank string
Bharathi Cherukuri
Interview Categories
How to declare a property in an Interface?
DateTime DateOfBirth { get;set;}int Age { get;set;}string FirstName { get;set;}As this is an Interface, so no implementation required only definition of properties are required. Implementation of these properties will be written into the class inherting this interface.
What is ILDASM?
TheILDASMstands forIntermediate Language Disassembler. This is a de-compiler which helps to get the source code from the assembly.This ILDASM converts an assembly to instructions from which source code can be obtained.The ILDASM can analize the .dll or .exe files and converts into human readable form. This is used to examine assemblies and understanding the assembly capability.
Which namespace is used to work with RegularExpression in C#?
NOTE: This is objective type question, Please click question title for correct answer.
What is partial class?
Partial class is a new functionality added in since .NET Framework 2.0 version. It allows to split us to split the definition of once class, struct, interface into multiple source files. Each source file contains a section of definition, and all parts are combined when the application is compiled.For more detail seehttp://msdn.microsoft.com/en-us/library/wa80x488(VS.80).aspx
What is the difference between Debug.Write and Trace.Write?
TheDebug.Writewill work while the application is in both Debug Mode and Release Mode. This is normally used while you are going to debug a project. This will not be work when you will define some debug points to your project.But theTrace.writewill work while the application is only in Release Mode. This is used in released version of an application. This will compiled when you will define debug points in your project.
Can you prevent your class from being inherited by another class?
Yes. The keyword “sealed” will prevent the class from being inherited.
Structures inherit ToString from System.Object. Why would someone override that method within a structure?
NOTE: This is objective type question, Please click question title for correct answer.
Write a code snippet that implements Virtual keyword ,overrides the virtual method in C#.
A virtual method can be redefined.The virtual keyword is used to modify a method and allow it to be overridden in a derived class. We can add derived types without modifying the rest of the program. The runtime type of objects thus determines behavior.Here is the code snippet :class Base{public virtual void FncOverride(){Console.WriteLine(Base Override);}}class Derived : Base{public override void FncOverride(){Console.WriteLine(Derived Override);}}class Program : Derived{static void Main(string[] args){// Compile-time type is Base.// Runtime type is also Base.Base bObj = new Base();bObj.FncOverride();// Compile-time type is Base// Runtime type is Derived.Base bdObj = new Derived();bdObj.FncOverride();}}In the above code the base class has FncOverride() method with Virtual keyword and overriding that method in Derived class. In my Main() function I am calling the base class FncOverride() method in following wayBase bObj = new Base();bObj.FncOverride();Now the calling function will be known to compiler at compile time itself.But when accessing the method like this:Base bdObj = new Derived();bdObj.FncOverride();This time the derived class function will be called. And the compiler decides at run time that which method should be invoked.While executing the above code we getBase OverrideDerived Override
What is a satellite assembly?
When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.
Difference Between dispose and finalize method?
Dispose is a method for realse from the memory for an object.For eg:object.Dispose.Finalize is used to fire when the object is going to realize the memory.We can set a alert message to says that this object is going to dispose.
What does the assert() method do in debug compilation ?
In this debug compilation ,.The assert() method takes in a Boolean condition as a parameter..It shows an error if that condition is false.The program runs without any intervention if the condition obtained is true.
Why we are using System.Environment class?
The aim of usingSystem.Environmentclass is to get the command-line arguments.This class also helps us to retrive the environment variable settings for a particularcontents of the call stack. It can also find the time of last system boot andversion of the CLR.
How to implement IN clause in LINQ/LAMBDA Query expression?Explain with an example.
This can be done using theContainsextension method. Example follows.Suppose we have a person class as underpublic class Person{public string PersonName { get; set; }public string JobTitle { get; set; }public override string ToString(){returnPerson Name:+ PersonName +JobTitle:+ JobTitle;}}Then populate the Person collection as underprivate static ListPersonPreparePersonCollection(){ListPersonlstPersonCollection = new ListPerson();lstPersonCollection.Add(new Person { PersonName =Amitav Sen, JobTitle =Design Engineer});lstPersonCollection.Add(new Person { PersonName =Bhavini Dey, JobTitle =Software Engineer});lstPersonCollection.Add(new Person { PersonName =Debasis Basu, JobTitle =Software Engineer});lstPersonCollection.Add(new Person { PersonName =Kartik Moin, JobTitle =Lead Engineer});lstPersonCollection.Add(new Person { PersonName =Shahjahan Khan, JobTitle =Technical Lead});return lstPersonCollection;}Suppose we want to get the list of Person who has job Title asDesign Engineer,Software Engineer.The complete query will be as underListPersonsource = PreparePersonCollection();string[] strJobTitleToInclude = new string[] {Design Engineer,Software Engineer};source.Where(i=strJobTitleToInclude.Contains(i.JobTitle)).ToList().ForEach(i =Console.WriteLine(i.ToString()));OutputPerson Name: Amitav Sen JobTitle:Design EngineerPerson Name: Bhavini Dey JobTitle:Software EngineerPerson Name: Debasis Basu JobTitle:Software Engineer
Can you prevent a class from overriding ?
Yes you can prevent a class from overriding if you define a class asSealedthen you can not inherit the class any further.
What are the different C# preprocessor directives?
#region,#endregion:- Used to mark sections of code that can be collapsed.#define,#undef:-Used to define and undefine conditional compilation symbols.#if,#elif,#else,#endif:- These are used to conditionally skip sections of source code.
What is CharEnumerator in C#?
CharEnumeratoris an object in C# that can be used to enumerate through all the characters of a string. Below is the sample to do thatstring str =my name;CharEnumerator chs = str.GetEnumerator();while(chs.MoveNext()){Response.Write(chs.Current);}Moderator: please do not move this to Code section, this is a typical interview question that was asked :)
You have to make user to enter just integer values with TextBox. Can you do this with CompareValidator?
Yes. With the validator control, you need to set type attribute to the desired datatype which in this case is “Integer” and Operator to DataTypeCheck.asp:CompareValidator ID=CompareValidator1ControlToValidate=TextBox1Type=IntegerOperator=DataTypeCheckrunat=serverErrorMessage=CompareValidator/asp:CompareValidator
Can a nested class access the outer class? Give an example?
Yes, the nested class or inner class can access the outer class. Nested types can access private and protected members of the containing type, including inherited private or protected members.using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Nested{class ClsContainer{string outerClsVariable =This is outer class variable;public class InnerClass{ClsContainer Obj = new ClsContainer();string innerClsVariable =This is inner class variable;public InnerClass(){Console.WriteLine(Obj.outerClsVariable);Console.WriteLine(this.innerClsVariable);}}}class Exec{public static void Main(){ClsContainer.InnerClass nestedClsObj = new ClsContainer.InnerClass();}}}
What class is underneath the SortedList class?
A sorted HashTable
Difference between | and ||
| : logical OR||: Conditional ORBoth operators are used to check the OR condition.The differences:1)if the first condition evaluates to TRUE, then| : it will check the second condition also.||: it does not check the second condition2) If the first condition evaluates to FALSE, | and || both will check the second conditionTake these 2 examples:class dd{static void Main(){int a = 10, b = 0;if (a==10 | (a%b)==0){Console.WriteLine(yes);}//output will be an error message}class dd{static void Main(){int a = 10, b = 0;if (a==10 || (a%b)==0){Console.WriteLine(yes);}//output will be yes}
Shallow Copy VS Deep Copy
Shallow copyCopies the structure of the objectThe easiest way to think of it is a shallow copy allows you to replicate the array once... it then ignores the relationship it has with the original array.OriginalArray = ShallowArray.Clone();The MemberwiseClone method creates a shallow copy by creating a new object, and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed. If a field is a reference type, the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same objectFor example, consider an object called X that references objects A and B. Object B, in turn, references object C. A shallow copy of X creates new object X2 that also references objects A and B.Deep copyCopies structure as well as data.The deep copy will be persistent and any changes you make to the original array will be reflected in both copies.OriginalArray = DeepArray;In contrast, a deep copy of X creates a new object X2 that references the new objects A2 and B2, which are copies of A and B. B2, in turn, references the new object C2, which is a copy of C. The example illustrates the difference between a shallow and a deep copy operation.
Can I use exceptions in C# ?
Yes, you can use exceptions in C#. In fact exceptions are the recommended error-handling mechanism in C# (and in .NET in general). Most of the .NET framework classes use exceptions to signal errors.
How can we invoke a method being defined inside a Base Class (Abstract class) without the Derived class being inheriting it?
We can do so if we declare the method as static. Then by using Classname.MethodName() we can invoke it.Example:class Program{static void Main(string[] args){MyBase.Hello();Console.ReadKey();}}public abstract class MyBase{public static void Hello(){Console.WriteLine(Hello);}}
How can we trace our view state information?
We can trace View State of our application by placing this tag at Page Directive.%@ Page Language=C#AutoEventWireUp=trueTrace=TrueNow if we run the page then we can see the details of the view state along with Control tree.
Can you allow class to be inherited, but prevent the method from being over-ridden?
Yes, we can allow the class to be inherited without over-riding the method.Just leave the class as public and make the method sealed.
C# delegate keyword is derived form which namespace?
C# delegate keyword is derived form System.MulticastDelegate.
Why 'static' keyword is used before Main()?
Program execution starts from Main(). S it should be called before the creation of any object. By using static the Main() can now be called directly through the class name and there is no need to create the object to call it. So Main() is declared as static.
In C# Threading - Thread.Sleep(int) method the integer parameter that represents Time that particular Thread should wait. What that Time Unit represents ?
NOTE: This is objective type question, Please click question title for correct answer.
Which of these classes allow us to add a printer dynamically?
NOTE: This is objective type question, Please click question title for correct answer.
What is the difference between object pooling and connection pooling?
In case of object pooling, you can control the number of connections. In this case the pool will decide whether the maximum is reached or not for creation of objects. If it reached to the maximum level then the next available object will returned back. The drawback is, it increases the time complexity for heavy objects.In case of connection pooling, you can control the maximum number of connections reached. When you are using this pool, since there is nothing in the pool, still it will create connection on the same thread.
How many catch Statement can be associated with single try statement?
It can be 0 to as many.try must be followed by catch or finally.ex:1)0 catch statementtry{}finally{}2) any numbertry{}catch{}catch{}finally{}
How to write a method in a class and build as .dll
To generate a .dll you can following below steps1. Right click your solution and select New Project.2. Select Visual C# as Project type and Class Library as Templates (give proper name and location path) and click OK.3. Write some code in the class like below, you can add as many class you want.using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.IO;namespace ClassLibrary1{public class Class1{public string GetMyName(string myName){return myName;}}4. Right click the Class Library project and select build.5. Your .dll should be ready in the bin folder of the project location (either in the debug or release folder) depends on which mode your project is.6. To refer this .dll, you can right click your project and select Add References.7. Select browse tab from the dialogue box and choose the .dll you have just generated.8. Now to use the method of the class library in any code behind page or another class library, you can use the namespace you had used in the class library (in above case ClassLibrary1) likeusing ClassLibrary1;9. Instantiate the class and use its method like belowClass1 c = new Class();string myName = c.GetMyName(Poster);Thanks :)
What is Big Integer Class?What problem it addresses?
BigInteger class resides in the System.Numerics namespace.It helps in representing any large integer without any loss of precision. It has been introduced earlier in dotnet framework 3.5 but was removed. However, it is again back in framework 4.0.Example: To find the factorial of 100.static void Main(string[] args){Console.Write(Factorial of hundred is :);HundredFactorial();Console.Read();}private static void HundredFactorial(){BigInteger number = 100;BigInteger fact = 1;for (; number--0; ) fact *= number+1;Console.WriteLine(fact);}OutputFactorial of hundred is : 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000It exposes some methods asa) GreatestCommonDivisor [ BigInteger.GreatestCommonDivisor(12, 24) ]b) Compare [ BigInteger.Compare(num1, num2) ]c) Parse [ BigInteger.Parse(10000000) ]d) Negate [ BigInteger.Negate(100) ]etc.
How to get the total number of elements in an array ?
By using Length property, we can find the total number of elements in an array.Below is an example which explains clearly.Example:using System;namespace ConsoleApplication{class Program{static void Main(){int[] Numbers = { 2, 5, 3, 1, 4 };Console.WriteLine(Total number of elements =+Numbers.Length);}}}
What is the best way to add items from an Array into ArrayList?
Use AddRange method of the ArrayList.string[] arr = new string[] {ram,shyam,mohan};ArrayList arrList = new ArrayList();arrList.AddRange(arr);
What is the difference between Data Reader & Dataset?
Data Reader is connected, read only forward only record set.Dataset is in memory database that can store multiple tables, relations and constraints; moreover dataset is disconnected and is not aware of the data source.
Which of the following attributes should you add to a class to enable it to be serialized?
NOTE: This is objective type question, Please click question title for correct answer.Found this useful, bookmark this page link to the blog or social networking websites.
Define different Access modifiers in C#
The access modifier is the key of Object Oriented Programming, to promote encapsulation, a type in C# should limit its accessibility and this accessibility limit are specified using Access modifiers.They are - Public, Internal, Protected, Private, Protected InternalPublic:When used that type (method or variable) can be used by any code throughout the project without any limitation. This is the widest access given to any type and we should use it very judiciously. By default, enumerations and interface has this accessibility.InternalWhen used that type can be used only within the assembly or a friend assembly (provided accessibility is specified using InternalVisibleTo attribute). Here assembly means a .dll.For example if you have a .dll for a Data Access Layer project and you have declared a method as internal, you will not be able to use that method in the business access layer)Similarly, if you have a website (not web application) and you have declared internal method in a class file under App_Code then you will not be able to use that method to another class as all classes in website is compiled as a separate .dll when first time it is called).Internal is more limited than Public.ProtectedWhen used that type will be visible only within that type or sub type. For example, if you have a aspx page and you want to declare a variable in the code behind and use it in aspx paeg, you will need to declare that variable as at least protected (private will not work) as code behind file is inherited (subclass) by the aspx page.Protected is more secure than Internal.PrivateWhen used that type will be visible only within containing type. Default access modifier for methods, variables. For example, if you have declared a variable inside a method, that will be a private variable and may not be accessible outside that method.Private is the most secure modifiers than any other access modifiers as it is not accessible outside.Protected InternalThis is not a different type of access modifiers but union of protected and internal. When used this type will be accessible within class or subclass and within the assembly.
What are the differnt categories of variables available in C#?
C# has seven types of variables.They arelocal variables -- Variables declared inside method or function.instance variables -- Declares at class level scopestatic variables -- which contains Static keyword before variable data type.array elements, -- Array variable. Contains sequence of memory locations.value parameters, -- Value type variable passed in parametersreference parameters -- Reference type variable passed in parametersoutput parameters -- Out type variable passed in parametersThere isno global variablein C#. Because it breaches the encapsulation concept.class Program{int VarClassScope = 42;static int VarStatic = 5;public void FncVariables(int VarValueParam, ref int VarRefParam, out int VarOutParam){VarOutParam = 100;VarRefParam = 50;VarValueParam = 25;}static void Main(string[] args){Program pObj = new Program();int VarFunctionScope = 23;int[] VarArrVariable = new int[1];VarArrVariable[0] = 22;Console.WriteLine(Class variable =+ pObj.VarClassScope);Console.WriteLine(Function variable =+ VarFunctionScope);Console.WriteLine(Static variable =+ VarStatic);Console.WriteLine(Array Element variable =+ VarArrVariable[0]);int VarOutParam = 10; //No use of initializing here for OUTint VarRefParam = 10;int VarValueParam = 10;pObj.FncVariables(VarValueParam, ref VarRefParam, out VarOutParam);Console.WriteLine(Value Param Variable =+ VarValueParam);Console.WriteLine(Reference Param Variable =+ VarRefParam);Console.WriteLine(Out Param Variable =+ VarOutParam);Console.Read();}}In the above code I am initializing all kinds of variables. Note the linepObj.FncVariables(VarValueParam, ref VarRefParam, out VarOutParam);I am calling theFncVariables function which accepts value, referene and out type variables. Before calling the function all variables have value 10.But after calling theFncVariables function, value type variable remains unchanged but ref and out type variables changed.The output isClass variable = 42Function variable = 23Static variable = 5Array Element variable = 22Value Param Variable = 10Reference Param Variable = 50Out Param Variable = 100
What is difference between var and Dynamic ?
Var word was introduced with C#3.5(specifically for LINQ) while dynamic is introduced in C#4.0. variables declared with var keyword will get compiled and you can have all its related methods by intellisense while variables declared with dynamic keyword will never get compiled. All the exceptions related to dynamic type variables can only be caught at runtime.
What happens when you encounter a continue statement inside for loop ?
The control is transferred back to the beginning of the loop and the code for the rest of the loop is ignored.
Why should you close and dispose of resources in a Finally block instead of a Catch block?
NOTE: This is objective type question, Please click question title for correct answer.
How to turn off autolisting feature in the code window of C# applications?
It can be done in 2 ways1)Tools--Options--Text Editor--C#-uncheck the checkbox with the Text Auto List members2)Tools--Options--Text Editor--All Languages--General--uncheck the checkbox with the Text Auto List members
If i will write a piece of code in finaly block, will it execute if there is an exception in try block.
Yes, the code in finally block will execute.
What are the different Name Spaces that are used to create a localized application ?
There are 2 different name spaces required to create a localized application they are.System.globalization.System.ResourcesWe need to use both name spaces(Necessary).
What does Dispose method do with the connection Object ?
Dipose method is called for an object.Before the Garbage collector automatically puts the object in to some of its generation, this dispose method is called for the object to release its memory.
Can a class have static constructor?
Yes, a class can have static constructor. Static constructors are called before when any static fields are executed. These are used to initialize static class members and called automatically before the first instance is created or any static members are referenced. This is also known as before instance constructor. Below is one example of above described theory.using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace SampApp{class Sample{static int i;static Sample(){i = 10;Console.WriteLine(In Static Constructor);}public Sample(){Console.WriteLine(In Instance Constructor);}public static void Main(){Sample s = new Sample();}}}
What are circular references? Explain how garbage collection deals with circular references?
A circular reference is a series of references when a formula refers back to its own cell, either directly or indirectly and the last object references the first, resulting in a closed loop. Also it is a run-around where in two resources are interdependent on each other.The methods to deal with circular references are:• Weighted reference counting• Indirect reference countingThere are some ways to handle problem of detecting and collecting circular references with the help of garbage collection.• The system may explicitly forbid reference cycles.• Systems ignore cycles if it have small amount of cyclic garbage.• You can also periodically use a tracing garbage collector cycles.
How to copy one array into another array ?
We can copy one array into another array by using copy To() method.Example:using System;namespace ConsoleApplication{class Program{static void Main(){int[] Numbers = { 2, 5, 3, 1, 4 };int[] CopyOfNumbers=new int[5];Numbers.CopyTo(CopyOfNumbers,0);foreach (int i in CopyOfNumbers){Console.WriteLine(i);}}}}
Give Some Examples of Generic Classes?
ListT,QueueT,StackT,LinkedListT,HashSetT
What is Multi-Threading?
Threading:A thread is nothing more than a process.The process sets up sequential steps, each step executing a line of code.MultiThreading:A multithreaded application allows you to run several threads, each thread runs in its own process.So that you can run step1 in one thread and step 2 in another thread at the same time.
Which property of the textbox cannot be changed at runtime ?
Locked Property of the textbox is the property that cannot be changed at runtime.Example:[BrowsableAttribute(false)]public bool Locked { get; set; }
How can you implement Standard Query Operators in LINQ?
These are implemented in LINQ as extension methods in .NET Framework. This can be used to work with any collection of objects that implements the IEnumerable interface. The inherited classes from the IEnumerable interface provide an enumerator for repeating over a collection of a specific type. All most all arrays and generic collection classes implementing IEnumerable interface.
What is the difference between ArrayList and Generic List in C#?
Generic collections are TypeSafe at compile time. So No type casting is required. But ArrayList contains any type of objects in it. Here is the code snippet.namespace Example{class Program{static void Main(string[] args){ArrayList list = new ArrayList();list.Add(hello);list.Add(new Program()); // Oops! Thats not meant to be there...list.Add(4);foreach (object o in list){Console.WriteLine(o.ToString());}ListstringlstString = new Liststring();lstString.Add(ABCD);lstString.Add(new Program()); //Compiler errorlstString.Add(4); // Compiler Errorforeach (object o in lstString){Console.WriteLine(o.ToString());}}}In the above code I am usinglistobejct of ArralyList type and adding all types of values such as string, int, object of Program class. When printing I am considering everything as object and converting it into string. This part of code alone will printhelloConsoleApplication7.Program4But when coming to the second partlstStringwhich is object of Liststringobject will not compile when control comes to the following lineslstString.Add(new Program()); //Compiler errorlstString.Add(4); // Compiler ErrorThe output will beError:The best overloaded method match forSystem.Collections.Generic.Liststring.Add(string)has some invalid arguments.
What’s the advantage of using System.Text.StringBuilder over System.String?
String Builder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time it’s being operated on, a new instance is created.
What is Stack?
This is a collection that abstracts LIFO (Last In First Out) data structure in which initial capacity is 32.
Write a single line of code to read the entire content of the text file.
User following codestring strContent = System.IO.File.ReadAllText(Server.MapPath(~/MyTextFile.txt));
Differences between Show and ShowDialog methods?
These methods are used in Window applications to call one form from anotherexample: we have Form1 and we want to call Form2.we may write like this in Form1private void button1_Click(object s, EventArgs e){Form2 f=new Form2();f.Show();}we can also write f.ShowDialog();The difference:Show method does not make the target form (Form2 in this case) as a modal dialogbox. ShowDialog() will make Form2() as a modal dialog box. So, when we useShowDialog() method, we cannot click anywhere on Form1 unless we close theinstance of Form2. In case of Show, we can click on Form1 even when Form2 is open.
What is the difference between a constant and a static readonly field?
A static readonly field is very much similar as constant, but the difference is the C# compiler does not have access to the value of a static readonly field at compile time. It will access only at run time.
Is there an equivalent of exit() or quiting a C#.NET application ?
Yes, you can use System.Environment.Exit(int exitCode) to exit the application.If it is a Windows Forms App, you can use Application.Exit().
What do you mean by static property? Give an example?
A property with a static keyword is considered as static property. This makes the property available to access at any time, even if no instance of the class exists. Below is the example for a static property.using System;using System.Collections.Generic;using System.Linq;using System.Text;class Value{private static int i = 3;public static int i{et{return i;}}}class Main{public static void Main(){Console.WriteLine(Value.i);}}
Difference between Static and ReadOnly?
Static:A variable that retains the same data throughout the execution of a program.ReadOnly:you can’t change its value.
What is the main difference between RegisterStartUpScript and RegisterClientScriptBlock?
RegisterStartUpScript Add the javascript code at the end of the page before the closing of form tag. while RegisterClientScriptBlock place the code at th top of the page.
what is Static?
Static:1)A Static memberdata or a memberfunction can be called without the help of an object.2)Static members can be called with the help of Classname.Syntax:classname.staticmember3)'this' keyword cannot be used inside a static memberfunction4)Nonstatic members cannot be used inside a static memberfunction
For which type of arrays, we can use the params keyword?
To clearly understand the params keyword , consider these examples://Correct1)Single dimensionalstatic void demod(params int[] k){}2) Jagged array;Note that we can use a multidimensional array using a jagged array//Correct1) static void demo(params int[][,] k){}Single dimensional array also OK with a jagged array.//Correct2)static void demog(params int[][] k){}3)Multidimensional array cannot be used directly//Wrongstatic void demok(params int[,] k){}
An array is fixed length type that can store group of objects.
NOTE: This is objective type question, Please click question title for correct answer.
A try block having 4 catch block will fire all catch block or not?
No, A try having more than one catch block will fire the first relevant catch block after that cursor will be moved to the finally block (if exists) leaving all remaining catch blocks.So in all cases only one catch block will fire.Thanks