What Is Method Hiding?
What Is Method Hiding?
Method hiding is to hide/mask method in base class by creating a similar function in derived class and by using
new keyword in the derived class.
Unlike Method overriding, When we refer base class object created by casting derived class object a method in
base class will be called.
Also we can change the return type while masking the base class method.
Using new keyword is not compulsory, however a warning will be displayed if we wont specify new keyword
while masking.
Example:
Base Class:
--------------
public class BaseClass
{
public virtual void Method1()
{
Print("Base Class Method");
}
}
Derived class
---------------
public class DerivedClass: BaseClass
{
public override void Method1()
{
Print("Derived Class Method");
}
}
Usage
-------------------
public class Sample
{
public void TestMethod()
{
DerivedClass objDC = new DerivedClass();
objDC.Method1();
BaseClass objBC = (BaseClass)objDC;
objDC.Method1();
}
}
Result
-----------------------------------
Derived Class Method
Base Class Method
Overloading means having functions with the same name but with different signature.Signature includes method
name and Parameters. These functions can be part of base class or derived class.
Whereas Overriding means changing the functionality of a method without changing the signature. We can
override a funtion in base class by creating a similar function in derived class and by use virtual/override
keywords.
Base class method has to be marked with virtual keyword and we can override it in derived class using override
keyword.
Derived class method will completly overrides base class method i.e when we refer base class object created by
casting derived class object a method in derived class will be called.
Example:
Base Class:
-------------------------------
public class BaseClass
{
public virtual void Method1()
{
Print("Base Class Method");
}
}
Derived class
---------------
public class DerivedClass: BaseClass
{
public override void Method1()
{
Print("Derived Class Method");
}
}
Usage
--------------------------
public class Sample
{
public void TestMethod()
{
DerivedClass objDC = new DerivedClass();
objDC.Method1();
BaseClass objBC = (BaseClass)objDC;
objDC.Method1();
}
}
Result
---------------------
Derived Class Method
Derived Class Method
int.Parse is a simple method used to convert string to integer. It throws exception when null or invalid input is
provided. Hence it is slow.
int.TryParse does not thow any exception instead we must describe second parameter as out parameter which
holds result. And it returns boolean value representing success or failure.
0 comments
Category: C#
However, making an object immutable is usually inappropriate if the object contains a large amount of
changeable data.
So String is not suggested to hold huge data as replacements or concatinations will be costly and time
consuming.
Copying is simple using reference. Whereas reference copying technique (Copying data without pointing to the
same reference) is difficult in case of StringBuilder.
String will allocate only what is needed. When we concatinate strings, it sums up the length of all and creates
buffer to fit that.
Whereas string builder allocates capacity of 16 initially and increases capacity in the multiples of 2.
What is CLR?
The .NET Framework provides a runtime environment called the Common Language Runtime
or CLR. The CLR can be compared to the Java Virtual Machine or JVM in Java. CLR handles the
execution of code and provides useful services for the implementation of the program. In
addition to executing code, CLR provides services such as memory management, thread
management, security management, code verification, compilation, and other system services.
It enforces rules that in turn provide a robust and secure execution environment for .NET
applications.
What is CTS?
Common Type System (CTS) describes the datatypes that can be used by managed code. CTSdefines how these
types are declared, used and managed in the runtime. It facilitates cross-language integration, type safety, and
high performance code execution. The rules defined inCTS can be used to define your own classes and values.
What is CLS?
Common Language Specification (CLS) defines the rules and standards to which languages
must adhere to in order to be compatible with other .NET languages. This enables C#
developers to inherit from classes defined in VB.NET or other .NET compatible languages.
What is MSIL?
When the code is compiled, the compiler translates your code into Microsoft intermediate
language (MSIL). The common language runtime includes a JIT compiler for converting this
MSIL then to native code.
MSIL contains metadata that is the key to cross language interoperability. Since this metadata
is standardized across all .NET languages, a program written in one language can understand
the metadata and execute code, written in a different language. MSIL includes instructions for
loading, storing, initializing, and calling methods on objects, as well as instructions for
arithmetic and logical operations, control flow, direct memory access, exception handling, and
other operations.
What is JIT?
JIT is a compiler that converts MSIL to native code. The native code consists of hardware
specific instructions that can be executed by the CPU.
Rather than converting the entire MSIL (in a portable executable[PE]file) to native code, the
JIT converts the MSIL as it is needed during execution. This converted native code is stored so
that it is accessible for subsequent calls.
a proxy.
What is an assembly?
An assembly is a collection of one or more .exe or dll’s. An assembly is the fundamental unitfor application
development and deployment in the .NET Framework. An assembly contains acollection of types and resources
that are built to work together and form a logical unit offunctionality. An assembly provides the CLR with the
information it needs to be aware of typeimplementations.
·
Assembly manifest - Contains the assembly metadata. An assembly manifest contains
the information about the identity and version of the assembly. It also contains the
information required to resolve references to types and resources.
·
A set of resources.
A dynamic assembly is created dynamically at run time when an application requires the types
What is GAC? What are the steps to create an assembly and add it to the GAC?
The global assembly cache (GAC) is a machine-wide code cache that stores assemblies
specifically designated to be shared by several applications on the computer. You should share
assemblies by installing them into the global assembly cache only when you need to.
Steps
- Create a strong name using sn.exe tool eg: sn -k mykey.snk
- in AssemblyInfo.cs, add the strong name eg: [assembly: AssemblyKeyFile("mykey.snk")]
- recompile project, and then install it to GAC in two ways :
·
drag & drop it to assembly folder (C:\WINDOWS\assembly OR C:\WINNT\assembly)
(shfusion.dll tool)
·
gacutil -i abc.dll
The caspol tool grants and modifies permissions to code groups at the user policy, machine
A garbage collector performs periodic checks on the managed heap to identify objects that are
What are generations and how are they used by the garbage collector?
Generations are the division of objects on the managed heap used by the garbage collector.
This mechanism allows the garbage collector to perform highly optimized garbage collection.
The unreachable objects are placed in generation 0, the reachable objects are placed in
generation 1, and the objects that survive the collection process are promoted to higher
generations.
Ilasm.exe is a tool that generates PE files from MSIL code. You can run the resulting
Ildasm.exe is a tool that takes a PE file containing the MSIL code as a parameter and creates a
Microsoft provides these languages for programming .NET - C#, VB.NET, JS.NET, C++.NET.
C++.NET may be used as a Managed Code Language by using managed extensions. This is
done using an _gc postfix. A managed C++ class can inherit from VB.NET classes, C# classes,
JS.NET classes. A managed class can inherit from only one class. .NET does'nt allow multiple
inheritance in managed classes.
Any Language that has a compiler that can compile the language code to MSIL is a .NET
compliant language.
Managed Code - The .NET framework provides lots of core runtime services to the programs
that run within it. For example - security & exception handling. Such a code has a minimum
level of information. It has metadata associated with it. Such a code is called Managed Code
VB.NET, C#, JS.NET code is managed by default. In order to make C++ code managed, we
make use of managed extensions, which is nothing but a postfix _gc after the class name.
Managed Data - Data that is allocated & freed by the .NET runtime's Garbage collecter.
Managed Class - A class whose objects are managed by the CLR's garbage collector. In
VC++.NET, classes are not managed. However, they can be managed using managed
extentions. This is done using an _gc postfix. A managed C++ class can inherit from VB.NET
classes, C# classes, JS.NET classes. A managed class can inherit from only one class. .NET
does'nt allow multiple inheritance in managed classes.
ILDASM - The contents of an assembly may be viewed using the ILDASM tool, that comes
with the .NET SDK or the Visual Studio.NET. The ildasm.exe tool may also be used in the
Serialization - The process of converting an object into a stream of bytes. This stream of
bytes can be persisted. Deserialization is an opposite process, which involves converting a
stream of bytes into an object. Serialization is used usually during remoting (while
transporting objects) and to persist file objecst & database objects.
serialize private and public fields of a class. The target class must be marked with the
Serializable attribute. On deserialization, the constructor of the new object is not invoked.
TheBinaryFormatter has the same features as the SoapFormatter except that it formats
data into binary format. The BinaryForamatter (and the SoapFormatter) has two main
methods. Serialize and Deserialize. To serialize an object, we pass an instance of the stream
and the object to the Serialize method. To Deserialize an object, you pass an instance of a
stream to the Deserialize method.
You can use the BinaryFormatter to serialize many, but not all, classes in the .NET Framework.
For example, you can serialize ArrayLists, DataSets, and Arrays but not other objects, such as
DataReaders or TextBox controls. To serialize a class, the class must have the Serializable
attribute or implement the ISerializable interface.
Note that the XmlSerializer captures only the public members of the class, whereas the
BinaryFormatter & the SoapFormatter captures both the public & private members of the
class. The output using the BinaryFormatter is quite compact, as the information is in binary
format, whereas the XmlSerializer format is filled with XML tags. See example below...
Imports System.IOImports System.Runtime.Serialization.Formatters.Binary
Dim colArrayList As ArrayListDim
objFileStream As FileStreamDim
objBinaryFormatter As BinaryFormattercolArrayList = New ArrayList()
colArrayList.Add( "Whisky")
colArrayList.Add( "Vodka")
colArrayList.Add( "Brandy")
objFileStream = New FileStream(MapPath("C:\myArrayList.data"), FileMode.Create)
objBinaryFormatter = New BinaryFormatterobjBinaryFormatter.Serialize(objFileStream,
colArrayList)objFileStream.Close()
Here we see that an instance of the file stream (objFileStream) and an instance of the object
(colArrayList) is passed to the Serialize method of the BinaryFormatter object
(objBinaryFormatter). We also end up creating a file by the name myArrayList.data on our
hard-drive.In order to deserialize an object, see the code below…
Dim colArrayList As ArrayListDim objFileStream As FileStreamDim
objBinaryFormatter As BinaryFormatterDim strItem As String
objFileStream = New FileStream( MapPath("myArrayList.data"), FileMode.Open )
objBinaryFormatter = New BinaryFormatter
colArrayList = CType( objBinaryFormatter.Deserialize( objFileStream ), ArrayList )
objFileStream.Close()
For Each strItem In colArrayList
Response.Write( "" & strItem )
Next
Here, CType takes in two parameters, the first parameter is the serialized object in the file
stream format, and the second parameter is the desired type. Finally, the page iterates
through all the elements of the ArrayList and displays the value of each element.
XmlSerializer does not serialize instances of classes like Hashtable which implement the
IDictionary interface.
Serializable - This is a class attribute. When we use this attribute with a class, an instance of
this class can be taken in whatever state it is, and write it to a disk. The class can then be
deserialized, and the class will act as if it is simply stored in the memory.
How to call COM components from .NET? What is interoperability?
COM components & .NET components have a different internal architecture. For both of them
to communicate with each other, inter-operation feature is required, this feature is called
interoperability. Enterprises that have written their business solutions using the old native
COM technology need a way for re-using these components in the new .NET environment.
.NET components communicate with COM using RCW (Runtime Callable Wrapper (RCW).
To use a COM component,
* Right click the Project & click on Add References.
* Select the COM tab
* Select the COM component
Another way of using a COM component is using thetblimp.exe tool (Type Library Import).
Using the COM component directly in the code may be achieved by using
System.Runtime.InteropServices namespace. This contains class TypeLib Converter which
provides methods to convert COM classes and interface in to assembly metadata. If the COM
component does not have a Type Library, thencustome wrappers need to be created. Once
the COM wrapper is created, it has to be registered in the registry.
Example
Suppose we have to insert FirstName into a table t_Employees. Our Store procedure is:
(@FirstName varchar(30)
)as
(B)What is a IL?
Twist :- What is MSIL or CIL , What is JIT?
(IL)Intermediate Language is also known as MSIL (Microsoft Intermediate Language) or CIL
(Common Intermediate Language). All .NET source code is compiled to IL. This IL is then
converted to machine code at the point where the software is installed, or at run-time by a
Just-In- Time (JIT) compiler.
(B)What is a CLR?
Full form of CLR is Common Language Runtime and it forms the heart of the .NET
framework.All Languages have runtime and its the responsibility of the runtime to take care of
the code execution of the program.For example VC++ has MSCRT40.DLL,VB6 has
MSVBVM60.DLL , Java has Java Virtual Machine etc. Similarly .NET has CLR.Following are the
responsibilities of CLR:
memory leakes. When objects are not referred GC automatically releases those memory thus
√ Code Access Security :- CAS grants rights to program depending on the security
configuration of the machine.Example the program has rights to edit or create a new file butthe security
configuration of machine does not allow the program to delete a file.CAS will takecare that the code runs under
the environment of machines security configuration.
√ Code Verification :- This ensures proper code execution and type safety while the code
runs.It prevents the source code to perform illegal operation such as accessing invalid memory
locations etc.
√ IL( Intermediate language )-to-native translators and optimizer’s :- CLR uses JIT
and compiles the IL code to machine code and then executes. CLR also determines depending
(B)What is a CTS?
In order that two language communicate smoothly CLR has CTS (Common Type
System).Example in VB you have “Integer” and in C++ you have “long” these datatypes are
not compatible so the interfacing between them is very complicated. In order that two
different languages can communicate Microsoft introduced Common Type System. So
“Integer” datatype in VB6 and “int” datatype in C++ will convert it to System.int32 which is
datatype of CTS.CLS which is covered in the coming question is subset of CTS.
If you have undergone COM programming period interfacing VB6 application with VC++
application was a real pain as the datatype of both languages did not have a common ground
where they can come and interface , by having CTS interfacing is smooth.
(B)What is a CLS(Common Language Specification)?
This is a subset of the CTS which all .NET languages are expected to support.It was always a
dream of microsoft to unite all different languages in to one umbrella and CLS is one step
towards that.Microsoft has defined CLS which are nothing but guidelines that language to
follow so that it can communicate with other .NET languages in a seamless manner.
B)What is a Assembly ?
(B) What is NameSpace?
Namespace has two basic functionality :-
√ NameSpace Logically group types.Example System.Web.UI logically groups our UI related
features.
√ In Object Oriented world may times its possible that programmers will use the same class
name.By qualifying NameSpace with classname this collision can be removed.
Note : The version number are in the manifest itself which is defined with the DLL or EXE thus
making deployment much easier as compared to COM where the information was stored in
You can expand the tree for detail information regarding the DLL like methods etc.
Versioning concept is only applicable to global assembly cache (GAC) as private assembly lie in
(B) What is GAC ?
Twist :- What are situations when you register .NET assembly in GAC ?
GAC (Global Assembly Cache) is used where shared .NET assembly reside.GAC is used in the
following situations :-
√ If the application has to be shared among several application.
√ If the assembly has some special security requirements like only administrators can remove
the assembly.If the assembly is private then a simple delete of assembly the assembly file will
remove the assembly.
Note :- Registering .NET assembly in GAC can lead to the old problem of DLL hell. Where COM
version was stored in central registry.So GAC should be used when
absolutely necessary.
[Visual Basic]
<Assembly:AssemblyKeyFileAttribute("myKey.snk")>
<Assembly:AssemblyDelaySignAttribute(true)>
[C#]
[assembly:AssemblyKeyFileAttribute("myKey.snk")]
[assembly:AssemblyDelaySignAttribute(true)]
The compiler inserts the public key into the assembly manifest and reserves space in the PE
file for the full strong name signature. The real public key must be stored while the assembly
is built so that other assemblies that reference this assembly can obtain the key to store in
their own assembly reference.
√ Because the assembly does not have a valid strong name signature, the verification of that
signature must be turned off. You can do this by using the –Vr option with the Strong Name
tool.The following example turns off verification for an assembly called myAssembly.dll.
Sn –Vr myAssembly.dll
√ Just before shipping, you submit the assembly to your organization's signing authority for
the actual strong name signing using the –R option with the Strong Name tool.The following
example signs an assembly called myAssembly.dll with a strong name using the sgKey.snk key
pair.
Sn -R myAssembly.dll sgKey.snk
forget to release the objects while coding..... laziness ( Remember in VB6 where one of the
good practices is to set object to nothing).CLR automatically releases objects when they areno longer referenced
and in use.CLR runs on non-deterministic to see the unused objects andcleans them. One side effect of this non-
deterministic feature is that we cannot assume anobject is destroyed when it goes out of the scope of a function.
Therefore, we should not putcode into a class destructor to release resources.
System.GC.Collect() forces garbage collector to run.This is not recommended but can be used
if situations arises.
(B)What is reflection?
All .NET assemblies have metadata information stored about the types defined in modules.This
metadata information can be accessed by mechanism called as “Reflection”.System.Reflection
can be used to browse through the metadata information. Using reflection you can also
dynamically invoke methods using System.Type.Invokemember.
Public ClassFor m1
Private SubForm1_Load(ByValsender AsSystem.Object, ByVale As
System.EventArgs) Handles MyBase.Load
DimPobjtype AsTy p e
DimPobjObject As Object
DimPobjButtons As NewWindows.Forms.Button()
Pobjtype = PobjButtons.GetType()
For EachPobjObject InPobjtype.GetMembers
LstDisplay.Items.Add(PobjObject.ToString())
Next
End Sub
End Class
Unboxing is vice versa of boxing operation where the value is copied from the instance in to
Below is sample code of boxing and unboxing where integer data type is converted in to object
Dimx As Integer
Dimy As Object
x = 10
‘ boxing process
y = x
‘ unboxing process
x = y
Advantages VB.NET :-
√ Has support for optional parameters which makes COM interoperability much easy.
√ With Option Strict off late binding is supported.Legacy VB functionalities can be used by
using Microsoft.VisualBasic namespace.
√ Has the WITH construct which is not in C#.
√ The VB.NET part of Visual Studio .NET compiles your code in the background. While this is
considered an advantage for small projects, people creating very large projects have found
that the IDE slows down considerably as the project gets larger.
Advantages of C#
√ XML documentation is generated from source code but this is now been incorporated in
Whidbey.
√ Operator overloading which is not in current VB.NET but is been introduced in Whidbey.
√ The using statement, which makes unmanaged resource disposal simple. √ Access to
Unsafe code. This allows pointer arithmetic etc, and can improve performance in some
situations. However, it is not to be used lightly, as a lot of the normal safety of C# is lost (as
the name implies).This is the major difference that you can access unmanaged code in C# and
not in VB.NET.
exceptions?
All exception derives from Exception Base class. Exceptions can be generated
programmatically or can be generated by system. Application Exception serves as the base
class for all application specific exception classes. It derives from Exception but does not
provide any extended functionality. You should derive your custom application exceptions from
Application Exception.
Application exception are used when we want to define user defined exception. While system