CSharp-Dotnetfunda
CSharp-Dotnetfunda
com
You can do this in more than one way but ForEach loop is much better than any other
way in terms of cleanliness of the code or performance.
ForEach loop
foreach (DataRow row in dTable.Rows)
{
yourvariable = row["ColumnName"].ToString();
}
For loop
for (int j = 0; j< dTable.Rows.Count; j++)
{
yourvariable = dTable.Rows[j]["ColumnName"].ToString()l
}
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.
NOTE: This is objective type question, Please click question title for correct
answer.
What is reflection?
Reflection is the ability to find the information about types contained in an assembly at
runtime.
OR
Reflection is the ability to find out information about objects, the application details
(assemblies), its metadata at run-time.
Edited: See the example: http://www.dotnetfunda.com/articles/article132.aspx
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.
OR
A delegate is an object that holds the reference to a method.
In C++ it is called function pointer.
What is SortedList?
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.
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.
Yes, but they are not accessible. Although they are not visible or accessible via the class
interface, they are inherited.
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 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 is Stack?
This is a collection that abstracts LIFO (Last In First Out) data structure in which initial
capacity is 32.
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 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.
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.
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)
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
int m_PersonID = 0;
public int PersonID
{
get { return m_PersonID; }
set { m_PersonID = value; }
}
Can you allow a class to be inherited, but prevent the method from being over-ridden?
Yes. Just leave the class public and make the method sealed.
Can you prevent your class from being inherited by another class?
Yes. The keyword “sealed” will prevent the class from being inherited.
A sorted HashTable.
How can you sort the elements of the array in descending order?
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.
Write a single line of code to create a text file and write contents into it.
System.IO.File.WriteAllText(@"c:\MyTextFile.txt", "MyContents");
Write a single line of code to read the entire content of the text file.
Types of Errors ?
Configuration Errors
Parser Errors
Compilation Errors
Run-Time Errors
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.
A sorted HashTable
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 the best way to add items from an Array into ArrayList?
What is Attribute Programming? What are attributes? Where are they used?
Attributes are a mechanism for adding metadata, such as compiler instructions and other
data about your data, methods, and classes, to the program itself. Attributes are inserted
into the metadata and are visible through ILDasm and other metadata-reading tools.
Attributes can be used to identify or use the data at runtime execution using .NET
Reflection.
Here's a couple of rules to consider when deciding on whether or not to use extension
methods:
OR
A nested class is any class whose declaration occurs within the body of another class or
interface.
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).
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’s a delegate?
Syntax: classname.staticmember
3)'this ' keyword cannot be used inside a static member function
4)Nonstatic members cannot be used inside a static member function
Clone() method makes a clone of the original array. It returns an exact length array.
CopyTo() copies the elements from the original array to the destination array starting at
the specified destination array index. Note that, this adds elements to an already existing
array.
In VB.NET, variables has to be declared earlier, before using Clone or CopyTo methods
to store the values. The difference arise on mentioning the size of the array.
While declaring the varaiable that is used for CopyTo method, it should have the size
equal to or more than that of the original array.
While declaring the variable that is used for Clone method we need not mention the array
size. Eventhough the array size is small, it won't show any error, rather the array size gets
altered automatically on cloning. The cloned array size get created equal to the size of the
source array.
If value type is used for CopyTo/Clone any change in the values made on them will not
get reflected on the original whereas on reference type the change gets reflected.
Below is the code which would throw some light on your understanding.
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.
For example, if we want to validate an Email address using the static method of the string
class (built-in) class, we can add an extension method like this.
public static bool IsValidEmail(this string input)
return regEx.IsMatch(input);
Notice the parameter passed to above method. Here "this" indicates the string class. Now,
we can use above extension method like this.
string myEmail = "[email protected]";
For example
In this case a new type will be created on the fly that will have Name, Gender, and Active
as public property and its backing field like _Name, _Gender, _Active.
This is especially useful when we want to receive data from other object or iterate
through a collection and set values and do not want to create a class just to hold the data.
Note that anonymous types are just a placeholder, we can't customize its behavior or add
methods inside it.
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.
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:
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.
C# has a large set of operators, which are symbols that specify which operations to
perform in an expression.
Arithmetic
+-*/%
String concatenation
+
Increment, decrement
++ --
Shift
<< >>
Relational
== != < > <= >=
Assignment
= += -= *= /= %= &= |= ^= <<= >>=
Member access
.
Indexing
[]
Cast
()
Conditional
?:
Object creation
new
Type information
as is sizeof typeof
Overflow exception control
checked unchecked
Partial class
Instead 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
{}
{}
Abbreviated as GAC, the Global Assembly Cache is a machine-wide store used to hold
assemblies that are intended to be shared by several applications on the machine. Each
computer where the common language runtime (CLR) is installed has a global assembly
cache. The global assembly cache stores the assemblies specifically designated to be
shared by several applications on the computer.
Strong name key is used to specify the strong name used to deploy any application in the
GAC (Global Assembly Catch) in the system.
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.
http://www.c-sharpcorner.com/UploadFile/vmsanthosh.chn/109042007094154AM/
1.aspx
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 this
SqlConnection 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 read http://www.codeproject.com/KB/cs/tinguusingstatement.aspx
Static: A variable that retains the same data throughout the execution of a program.
ReadOnly: you can’t change its value.
How do I call a member method and pass a primitive type (Value Type) by
reference?
This will pass the numeric by reference.You can modify the value of
returnValue within the body of GetValue and it will persist when the method
call returns.
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ClassLibrary1
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) like "using ClassLibrary1;"
9. Instantiate the class and use its method like below
Class1 c = new Class();
To explicitly implement interface we need to prefix the method name with the name of
the interface following by .(dot).
string IInterface1.HelloNet()
{
return "Interface 1 : Hello NET";
}
Assuming that HelloNet method is in IInterface1 as well as another
interface that is inherited in the class.
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)
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.
What are three test cases you should do while unit testing?
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.
* 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 the Autos window feature.
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.
Give Some Examples of Generic Classes?
List<T>,Queue<T>,Stack<T>,LinkedList<T>,HashSet<T>
So you can declare a local variable of any type using var keyword but you can't declare
an array of variable using var keyword.
Correct
string[] str = { "ram", "sham" };
Wrong
var[] str = { "ram", "sham" };
To cache the output for each HTTP request that arrives with a different ID:
Declarative Approach:
<%@ OutputCache duration="60" varybyparam=" ID" %>
Programmatic Approach:
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.VaryByParams["ID"] = true;
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="CompareValidator1"
ControlToValidate="TextBox1" Type="Integer" Operator="DataTypeCheck"
runat="server" ErrorMessage="CompareValidator"></asp:CompareValidator>
Code extract :
TimeSpan DayDifference = Convert.ToDateTime("2009-1-
7").Subtract(Convert.ToDateTime("2009-1-1"));
To find the difference of the days, here we have used Subtract method. The Subtract
method does not take start date into consideration. Hence, to get the exact number of days
for the date range we need to add one more day to the result.
Response.Write("Number of Days : " + DayDifference.Days+1);
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()
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.
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);
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.
For value types : “==” and Equals() works same way : Compare two objects by
VALUE
Example:
int i = 5;
int k= 5;
i == k > True
i.Equals(k) > True
Recommendation :
For value types: use “==”
For reference types: use Equals method.
This will work fine bt what if when you are aware about the value of string variable test.
if test="abc"....
In that case if u try to use above method, .NET will throw an exception as you are trying
to convert string data to integer.
TryParse is a good method if the string you are converting to an interger is not always
numeric.
if(!Int32.TryParse(test,out iResult))
{ //do something }
The TryParse method returns a boolean to denote whether the conversion has been
successfull or not, and returns the converted value through an out parameter.
No, generics is not supported for the classes which does not inherits collect class.
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 of "System.NullReferenceException" type, if used.
How do we retrieve day, month and year from the datetime value in C#?
I need to restrict a class by creating only one object throughout the application.
How can I achieve this?
Example:-
unsafe
{
int a, *b;
a = 25;
b = &a;
Console.WriteLine("b= {0}",b);//returns b= 25
}
Its newly introduced keyword of C#4.0. To indicate that all operations will be performed
runtime.
What will happen if you declare a variable named "checked" with any data type?
Property acts as a cross link between the field and the method . Actually it behaves as
a field. We can retrieve and store data from the field using property.
The compiler automatically translates the field like property into a call like special
method called as 'accessor" . In property there are two accessor and that are used to save
value and retrieve value from the field. The two properties are 'get' and 'set'.
The get property is used to retrieve a value from the field and the set property is used to
assign a value to a field .
Depending on there use properties are categorised into three types,
ReadWrite Property :- When both get and set properties are present it is called as
ReadWrite Property.
ReadOnly Property :- When there is only get accessor it is called as ReadOnly Property.
out
ref
params
What are the different Iteration Constructs in C#?
for loop
foreach/in loop
while loop
do/while loop
Which keyword in C# is used to temporarily fix a variable so that its address may be
found?
fixed keyword
#if , #elif , #else , #endif :- These are used to conditionally skip sections of source code.
Which methods are used to execute javascript code from code behind file?
RegisterStartupScript and RegisterClientScriptBlock
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.
I would like to find all the directories of a folder How should I achieve this?
By Directory.GetDirectories method
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() and EndInvoke().
When TimerCallback delegate is used?
Many application have the need to call a specific method during regular intervals. For
such situations we can use the System.Threading.Timer type in conjunction with a related
delegate named TimerCallback.
Virtual keyword is used to declare a method inside the base class that can be overridden.
Following conditions are applied to a virtual method
1. Virtual method can not be declared as Private
2. Virtual method can not be declared as Static
3. 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.
IEnumerable<T>
IEnumerable<T> is best suitable for working with in-memory collection.
IEnumerable<T> doesn't move between items, it is forward only collection.
IQueryable<T>
IQueryable<T> best suits for remote data source, like a database or web service.
IQueryable<T> is a very powerful feature that enables a variety of interesting deferred
execution scenarios (like paging and composition based queries).
So when you have to simply iterate through the in-memory collection, use
IEnumerable<T>, if you need to do any manipulation with the collection like Dataset and
other data sources, use IQueryable<T>.
Can we declare a class as Protected?
No, a class can not be declared as Protected.
Abstract
Internal
Public
Sealed
Static
Extern (The extern modifier is used to declare a method that is implemented externally. -
http://msdn.microsoft.com/en-us/library/e59b22c5(VS.80).aspx)
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 error
private class BaseClass
{}
public class DerivedClass : BaseClass
{}
Name any two "Permission Classes" generally used while working with CAS ?
1) FileIOPermission
2) UIPermission
3) SecurityPermission
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);
How we can gt the values of control on the previous page in case of server.transfer
method?
Can we use Page.PreviousPage to get the value of controls of the previous page in case of
response.Redirect ?
No, we can't use PreviousPage to find the control on previous page with
response.redirect.
RegisterStartUpScript Add the javascript code at the end of the page before the closing of
form tag. while RegisterClientScriptBlock place the code at the top of the page.
Serialization/Deserialization in .NET
Welcome to the next installment of the .NET Nuts & Bolts. In this column, we'll explore
serialization and deserialization with the Microsoft .NET Framework. We'll look at the
reasons for using serialization and techniques for utilizing it within your applications. It
will involve using classes located in the System.Runtime.Serialization namespace.
Definition of Serialization
There are three formats provided by the Microsoft .NET framework to which objects can
be serialized. The formats are binary, SOAP, and XML. The format is controlled based
upon what object is used to perform the serialization. The XML format is produced by
using the System.Xml.Serialization.XmlSerializer class. The SOAP and binary formats
are produced by using classes under the System.Runtime.Serialization.Formatters
namespace.
There are subtle differences among the serialized formats. The binary-based format is the
most compact and light of the three formats. The XML formatter only serializes public
fields and properties, while binary and SOAP do not adhere to that limitation.
The following code defines a class that demonstrates the use of some of the XML
serialization controlling attributes.
using System;
using System.Xml.Serialization;
namespace CodeGuru.Serialization
{
[XmlRoot("TestDataXml")]
public class TestData
{
private int _Identity = 0;
public TestData()
{
}
}
}
The following code will serialize the sample class defined above and store the
information in a file on the local drive.
Resulting XML
Notice how the private fields and properties are not included in the XML. The
XmlSerializer behaves this way by design.
<?xml version="1.0"?>
<TestDataXml xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<DataName>testing</DataName>
</TestDataXml>
Delay signing allows to place a shared assembly in the GAC
by signing the assembly with just the public key. This
allows the assembly to be signed with the private key at a
later stage, when the development process is complete and
the component or assembly is ready to be deployed.
sn -Vr assembly.dll
o To disable verification for all assemblies with a particular public key, use
the following command.
sn -Vr *,publickeytoken
o To extract the public key and key token (a truncated hash of the public
key), use the following command.
7. To fully complete the signing process and create a digital signature to make the
assembly tamper proof, execute the following command. This requires the private
key, and as a result the operation is normally performed as part of the formal
build/release process. The following command uses key pair contained in the
Keypair.snk file to re-sign an assembly called Assembly.dll with a strong name.
sn -R assembly.dll keypair.snk Done
Attributes
1. What is OOPs?
2. What is Object?
8. Sealed Class?
13. How can you handle abstract function without implementing it in derive class?
15. How many number of times item data bound event will be called for 10 rows in grid?
What property will you use to check header in datagrid?
25. Can we have multiple update panel in AJAX, Write a code to call another update
panel on click on another?