What is C# Programming Language?
C# (pronounced as “C Sharp”) is a simple, modern, object-oriented and
type safe programming language.
C# Programming
language will allow developers to build a variety of secure and robust
applications such as windows applications, web applications, database
applications, etc. which will run on .NET Framework.
C# programming
language has built on .NET Framework so to run the c# applications, we required to install a .NET Framework component on our machines.
.NET Framework is a development platform for building an apps for
windows, web, azure, etc. by using programming languages such as C#, F# and
Visual Basic. It consists of a two major components such as Common Language
Runtime(CLR), it’s an
execution engine that handles running apps and .NET Framework Class
Library, which provides a
library of tested and reusable code that developers can use it in their
applications.
execution engine
that handles running apps and .NET Framework Class Library, which provides a library of tested and
reusable code that developers can use it in their applications.
Overview of C#
- C# is an object oriented
programming language and it supports the concepts of encapsulation,
abstraction, polymorphism, etc.
- In c# all the variables,
methods and application’s entry point are encapsulated within the class
definitions.
- C# is developed specifically
for .NET Framework and it enable programmers to migrate from C/C++ and
Java easily.
- C# is fully Event-driven and
visual programming language.
- Microsoft provided an IDE
(Integrated Development Environment) tool called Visual Studio to implement c# programs easily.
Features of C#
C# contains various
features that make it similar to other programming languages such as c c++ and
java. There are some additional features in C# which make it differ from other
languages.
- C# is modern programming
language and it is very powerful, simple for building the applications
- C# is useful in developing
windows, web and device applications.
- C# provides an automatic memory
management by clearing unused objects
- C# is a type safe programming
language and it make impossible to perform unchecked type casts.
- C# provides a structured and
extensible approach for error detection and recovery.
- C# is a structure oriented
programming language and the compilation, execution of c# applications are
faster due to automatic scalability.
C# Variables with Examples
In
C#, Variables will
represent a storage locations and each variable has a particular type that
determines what type of values can be stored in the variable.
C# is
a Strongly Typed programming
language so before we perform any operation on variables, it’s mandatory to define
a variable with required data type to
indicate what type of data that variable can hold in our application.
Value Types
In
c#, a data type is
a Value Type if it hold the value
of variable directly
on its own memory space and Value Types will use Stack memory
to store the variables values.
Pass
Value Type by Value
In
c#, if we pass a value type variable from one method to another method, the
system will create a separate copy for the variable in another method. In case,
if we make a changes to the variable in one method won’t affect the variable in
other method.
Reference
types
In
c#, Reference
Types will contain a pointer which points to other memory
location that holds the data. The Reference
Types won’t store the variable value directly in its
memory instead, it will store the memory address of the variable value to
indicate where the value is being stored.
Pass
Value Type by Value
In
c#, if we pass a value type variable from one method to another method, the
system will create a separate copy for the variable in another method. In case,
if we make a changes to the variable in one method won’t affect the variable in
other method.
Namespaces
Namespace is used to organize the multiple classes in our applications and it will reduce the code redundancy in our
.NET applications. By using
namespace
keyword, we can define the namespaces in
our c# applications.
In simple words, we can
say that Namespace is
a collection of classes and classes are the collection of objects and methods. So by using namespaces we can easily access all the class methods just by importing the namespace in our application.
Namespace
|
Description
|
System
|
It contains a classes that allows you to perform basic operations such as
mathematical operation and data conversation.
|
System.IO
|
|
System.Net
|
|
System.Data
|
|
System.Collection
|
|
System.Drawing
|
|
System.Web
|
Nested
Namespaces in C#
In
c#, a namespace can contain another namespace and it is called a Nested Namespace.
The nested namespace classes and
its members can be accessed by using dot (.) operator.
Operators
Operator is a programming element that specifies
what kind of an operation need to perform on operands or variables.

C# Methods / Functions
In
c#, Method is
a separate code block and that contain a series of statements to perform a
particular operations and methods must be declared either in class or struct by
specifying the required parameters.
Generally,
in c# Methods are useful to improve the code reusability by reducing the code
duplication.
Pass By
Value
In
c#, Passing a Value-Type parameter
to a method by value means passing a copy of the variable to the method. So the
changes made to the parameter inside of called method will not have an effect
on the original data stored in the argument variable.
As
discussed earlier, Value-Type variables
will contain the value directly on it memory and Reference-Type variables
will contain a reference of its data.
Out
Parameter
In
c#, out keyword
is used to pass an arguments to the method as a reference
type. The out keyword
is same like refkeyword,
only difference is out doesn’t
require a variable to be initialized before we pass it as an argument to the
method but the variable must
be initialized in called method before it return a value to the calling method.
The
out parameter in c# is also useful to return more than one value from the
methods in c# programming language.
Params
In
c#, params keyword
is used to specify a method parameter that takes a variable number of
arguments. The
params
keyword is useful when
we are not sure about number of arguments to send as a parameter.
In
c#, during method declaration only one
params
keyword
is allowed and no additional parameters are permitted after the params
keyword
in a method declaration.
We
can send an arguments of specified type as a comma-separated list or an array
to the declared parameter.
Class
Classes and
Objects are
interrelated. The class in
c# is nothing but a collection of various data members (fields, properties,
etc.) and member functions.
Internal is the default if no access
modifier is specified. Class members (including
nested classes and structs) can be declared with any of the
five types of access. Struct members cannot be declared as
protected because structs do not support inheritance. User-defined operators
must always be declared as public.
C# Object
In
c#, Object is
an instance of a class and
that can be used to access the data members and member functions of a class.
Creating
Objects in C#
Generally,
we can say that objects are the concrete entities of classes. In c#, we can
create an objects by using a newkeyword
followed by the name of the class like as shown below.
C# Class Members
As discussed, a class can contain multiple data members in c# programming
language. Following table lists a different type of data members that can be
used in c# classes.
Member
|
Description
|
Variables of the class
|
|
Computations and actions that can be
performed by the class
|
|
Actions associated with reading and writing
named properties of the class
|
|
Notifications that can be generated by the
class
|
|
Actions required to initialize instances of
the class or the class itself
|
|
Conversions and expression operators
supported by the class
|
|
Constant values associated with the class
|
|
Indexers
|
Actions associated with indexing instances
of the class like an array
|
Finalizers
|
Actions to perform before instances of the
class are permanently discarded
|
Types
|
Nested types declared by the class
|
Constructor
In
c#, Constructor is
a method which will invoke automatically whenever an instance of class or struct is
created. The constructor will have a same name as the class or struct and it
useful to initialize and set a default values for the data members of the new
object.
In
case, if we create a class without having any constructor, then the compiler
will automatically create a one default constructor for that class. So, there
is always one constructor will exist in every class.
In
c#, a class can
contain more than one constructor with different type of arguments and the
constructors will never return anything, so we don’t need to use any return
type, not even void while
defining the constructor method in class.
C# Parameterized
Constructor
In
c#, if we create a constructor with at least one parameter, then we will call
it as parameterized
constructor and the every instance of class will be
initialized with parameter values.
C#
Constructor Overloading
In
c#, we can overload the
constructor by creating another constructor with same method name but with
different parameters.
C#
Constructor Chaining
In
c#, Constructor
Chaining is an approach to invoke one constructor from
another constructor. To achieve constructor chaining we need to use
this
keyword
after our constructor definition.Copy Constructor
In
c#, Copy
Constructor is a parameterized
constructor which contains a parameter of same class type. The copy
constructor in c# is useful whenever we want to initialize a new instance to
the values of an existing instance.
In
simple words, we can say copy constructor is a constructor which
copies a data of one object into another object. Generally, c# won’t provide a
copy constructor for objects but we can implement ourselves based on our
requirements.
Static Constructor
In c#, Static Constructor is used to perform a particular action
only once throughout the application. If we declare a constructor as static, then it will be invoked only once
irrespective of number of class instances and it will be called automatically
before the first instance is created.
Generally, in c# the
static constructor will not accept any access modifiers and parameters. In simple
words we can say it’s a parameter less.
Following are the
properties of static constructor in c# programming language.
- Static constructor in c# won’t
accept any parameters and access modifiers.
- The static constructor will
invoke automatically, whenever we create a first instance of class.
- The static constructor will be
invoked by CLR so we don’t have a control on static constructor execution
order in c#.
- In c#, only one static
constructor is allowed to create.
Private
In c#, Private Constructor is
a special instance constructor and it is used in a classes that contains
only static members.
If a class contains one or more private constructors and no public
constructors, then the other classes are not allowed to create an instance for
that particular class except nested classes.
Destructor
In c#, Destructor is a special method of a class and
it is used in a class to
destroy the object or instances of classes.
The destructor in c# will invoke automatically whenever the class instances
become unreachable.
Following are the
properties of destructor in c# programming language.
- In c#, destructors can be used
only in classes and
a class can
contain only one destructor.
- The destructor in class can
be represented by using tilde (~) operator
- The destructor in c# won’t
accept any parameters and access modifiers.
- The destructor will invoke
automatically, whenever an instance of class is
no longer needed.
- The destructor automatically
invoked by garbage collector whenever the class objects
that are no longer needed in application.
·
class User
·
{
·
// Destructor
·
~User()
·
{
·
// your code
·
}
·
}
this
Keyword
In
c#, this keyword
is used to refer the current instance of class and by using
this
keyword
we can pass current instance of class as a parameter to the other methods.
In
case, if class contains a parameters and variables with same name, then
this
keyword
is useful to distinguish between the parameters and variables.
We
can also use
this
keyword to
declare indexers and to specify the instance variable in the parameter list of
an extension method.
Static
Keyword
In
c#, static is
a keyword or a modifier which is used to make a class or methods or a variable
properties as not instantiable that means we cannot instantiate the items which
we declared with a
static
modifier.
The static members
which we declared can be accessed directly with a type name. Suppose if we
apply a
static
modifier to a class
property or to a method or variable, then we can access those static members
directly with a class name, instead of creating an object of a class to access
those properties.
Static
Class
In
c#, a static
class can be created by using
static
modifier
and the static class can contain only static members.
Generally,
the static class is
same as non-static class, but only difference
is the static
class cannot be instantiated. Suppose if we apply
static
modifier
to a class, then we should not use the new keyword to create a variable
of the class type.
Another
difference is the static
class will contain only static members,
but the non-static
class can contain both static and
non-static members.
C# Static Class Features
Following are the main
features of static class in c# programming language.
- The static class in c# will
contain only static members.
- In c#, the static classes
cannot be instantiated.
- C# static classes are sealed, therefore it cannot be inherited.
- The static classes in c# will
not contain instance constructors.
As discussed in
previous article static keyword in c#, we can use static members in non-static classes such
as normal classes.
For normal classes we
can create an instance of class using new keyword to access non-static members and functions but it
cannot access the static members
and functions.
The advantage of using
static classes in c# applications will make sure that instance of classes
cannot be created.
const
(Constant) Keyword
In
c#, const is
a keyword which is used to declare a constant fields in our applications.
Generally, in c# the constant field values are set at compile time and those
values never be changed.
In
c#, if we use
const
keyword to
declare constant field, then that field value cannot be changed throughout the
application so we should not use const
keyword
with the fields whose value will be changed at any time.
To
define a constant fields in c#, we need to use
const
keyword
during the declaration of fields in our application and we can use constants
with numbers, boolean values, strings or with null references.
It’s
mandatory to initialize a constant fields with required values during the
declaration itself otherwise we will get a compile time errors in our c#
application.
Readonly
In
c#, readonly is
a keyword which is used to define a read only fields in our applications.
The read only field values needs to be initialized either at the declaration or
in a constructor of the same class unlike constant
keyword in c#. If we use
readonly
keyword
with fields, then those field values will be evaluated at the runtime.
To
define a read only fields in c#, we need to use
readonly
keyword
during the declaration of fields in our application and we can use readonly
modifier
with the numbers, boolean values, strings or with null references.
In
c#, if we use
readonly
keyword to
define read only field, then that field value cannot be changed once the constructorexecution has finished so we should not
use readonly
keyword with the
fields whose value will be changed at any time.
It’s
mandatory to initialize a read only field values either at the declaration or
in a constructor otherwise
we will get a compile time errors in our c# application.
C# Difference between Constant and ReadOnly
- In c#, the constant fields can be created by using const keyword and read only
fields can be created by using readonly keyword.
- In c#, the constant fields can only be initialized during the time of
declaration but read only fields can be initialized either at the
declaration or in a constructor.
- Constant field values will be
evaluated during the compile time but read only fields values will be
evaluated at run time in c#.
C# Structure Characteristics
Following are the
important characteristics of structures in c# programming language.
- In c#, structures are value types and those are defined by using struct keyword.
- During structure declaration,
the fields cannot be initialized unless they are defined as const or static.
- Structures in c# can include
fields, properties, member functions, operators, constructors, events,
indexers, constants and even other structure types.
- Structures cannot include default constructor (constructor without parameters) or destructor but it will allow us to declare constructors with parameters.
- A structure cannot inherit from
another structure or class.
- In c#, the structure can
implement interfaces.
- A structure can instantiated
with or without using a new keyword.
C# Difference between Structure and Class
Following are the
difference between structures and classes in c# programming language.
- In c#, classes are
the reference types and structures are the value types.
- Classes can
contain default constructor or destructor but structures will contain only constructors
that have a parameters.
- We can implement inheritance using Classes but
structures won’t support inheritance.
- Unlike classes,
structs can be instantiated with or without using a new operator.
C# Enum
(Enumerator)
In
c#, enum is
a keyword which is used to declare an enumeration. In c#, enumeration is a type
that consists a set of named constants as
list.
By
using an enumeration, we can group a constants that are logically related to
each other. For example, the days of week can be grouped together by using
enumeration in c#.
In case, if we want to change the default values of an
enumerator, then assigning a new value to the first item in enumerator will
automatically assign an incremental values to the successive items in an
enumerator.
C#
Properties (GET, SET)
In
c#, Property is
an extension of class variable and
it provides a mechanism to read, write or change the value of class variable without
effecting the external way of accessing it in our applications.
In
c#, properties can contain one or two code blocks called accessors and those
are called a
get
accessor and set
accessor.
By using get
and set
accessors,
we can change the internal implementation of class variables and
expose it without effecting the external way of accessing it based on our
requirements.
Generally,
in object oriented programming languages like c# we need to define a fields
as private,
and then use properties to access their values in public way
with
get
and set
accessors.
Here, the get accessor code
block will be executed whenever the property is read and the code block
of set accessor
will be executed whenever the property is assigned to a new value.
In c#, the properties
are categorized as three types, those are.
Type
|
Description
|
Read-Write
|
A property which contains a both get and set accessors,
then we will call it as read-write property.
|
Read-Only
|
A property which contains only get accessor, then
we will call it as read-only property.
|
Write-Only
|
A property which contains only set accessor, then
we will call it as write-only property.
|
In c#, Properties
won’t accept any parameters and we should not pass property as a ref or out parameter in our application.
Partial
Class
In
c#, a partial
class is useful to split the functionality of particular
class into multiple class files and all these files will be combined into one
single class file when the application is compiled.
While
working on large scale projects, multiple developers wants to work on the
same class file
at the same time. To solve this problem, c# provides an ability to spread the
functionality of particular class into
multiple class files
using
partial
keyword.
In
c#, we can use
partial
keyword to
split the definition of particular class, structure, interface or
a method over
two or more source files.
Rules to Implement Partial Class
In c#, we need to
follow certain rules to implement partial class in our applications.
- To split the functionality
of class, structure, interface or
a method over
multiple files we need to use partial keyword and
all files must be available at compile time to form the final type.
- The partial modifier
can only appear immediately before the keywords class, struct or interface.
- All parts of partial type
definitions must be in the same namespace or assembly.
- All parts of partial type
definitions must have the same accessibility, such as public, private,
etc.
- If any partial part is declared
as abstract, sealed or base, then the whole type is considered as abstract or sealedor base based on the defined type.
- In c#, different parts can have
different base types but the final type will inherit all the
base types.
- Nested partial types are
allowed in partial type definitions.
C#
Partial Method
In
c#, partial
method is a special type of method which will contain a
declaration part in one partial class and
the definition part in another partial class or
in same partial class.
Generally,
the partial methods will exists either in partial class or struct and
it will contain two main parts one is declaration and definition. Here,
the declaration part
represents a signature of the partial method and the definitionpart will
represents an implementation of partial method.
In
partial method, the definition part is an optional so it may or may not have an
implementation in partial classes. In
case, the implementation part of partial method is not available in any partial
class, then the compiler will remove the definition of method and all the calls
related to that particular method in final class.
Rules to Implement Partial Method
In c#, we need to
follow certain rules to implement partial method in our applications.
- In c#, the partial method can
be implemented within partial class or structure only and the signatures in both parts of partial
type must be same.
- The partial method declaration
must begin with partial keyword and method must return void.
- By default partial methods are
implicitly private so no access modifiers are
allowed and they cannot be virtual.
- Partial methods can have ref but
not out parameters.
- Partial methods can be static and generic.
String
In
c#, string is
a keyword which
is used to represent a sequential collection of characters that is called a
text and the string is an object of System.String type.
In
c#, we use string keyword to
create a string variables to
hold the particular text which is a sequential collection of characters.
C# String
Immutability
In
c#, string is immutable, it means
the string object cannot be modified once it created. If any changes made to
the string object like add or modify an existing value, then it will simply
discard the old instance in memory and create a new instance to hold the new
value.
the StringBuilder is
a dynamic object which will expands dynamically to accommodate the number of
characters based on the string modifications.
Access
Modifiers (Public, Private, Protected, Internal)
By specifying
an access level for all types and type members, we can control that whether
they can be accessed in other classes or
in current assembly or in other assemblies based on our requirements.
Virtual
Keyword
In c#, virtual keyword
is used to override a
base class members such as properties, methods, etc. in derived class to modify it based on our requirements.
Generally,
whenever the virtual method is invoked, the run-time object will check for an
overriding member in the derived class. In case, if no derived class has
overridden the member, then the virtual method will be treated it as original
member.
In
c#, by default all the methods are non-virtual and
we cannot override a non-virtual methods.
In case, if you want to override a
method, then you need to define it with virtual keyword.
The virtual keyword
in c# cannot be used with static, abstract, private or override modifiers.
In c#, the virtual inherited properties can
be overridden in a derived class by including a property declaration
that uses the overridemodifier.
Override Keyword
I
in
c#, we cannot override a non-virtual or static methods.
In case, if you want to override a method, then you need to define it
with virtual keyword.
To
override a base class method in derived class, then both override method
and virtual method
must have a same signatures and access
modifiers.
In
c#, we should not use static, new, or virtual modifiers
to modify an override method.
The overriding property declaration must specify exactly the same access
modifier, type and name as inherited property.
Sealed
Class
In
c#, sealed is
a keyword which
is used to stop inheriting the
particular class from
other classes and we can also prevent overriding the
particular properties or methods based
on our requirements.
Generally,
when we create a particular class we
can inherit all
the properties and methods in
any class. In
case, if you want to restrict an access of defined class and its members, then
by using sealed keyword
we can prevent other classes from inheriting the defined class.
C# Sealed Keyword Features
Following are the
important points which we need to remember about sealed keyword in c# programming
language.
- In c#, to apply a sealed keyword on method or property, it must always be used with override.
- In c#, we should not use abstract modifier with sealed class, because an abstract class must be
inherited by a class that
provides an implementation of the abstract methods or properties.
- In c#, the local variables cannot be sealed.
- In c#, structs are implicitly sealed, they
cannot be inherited.
C# Interface Overview
Following are the
important properties of interface in c# programming language.
·
In c#, interface is
like an abstract
class and it can
contain only declarations of members
such as methods, properties, indexers and events.
·
By default, the
members of interface are public and
we are not allowed to include any other access modifiers.
·
In c#, an interface
cannot be instantiated directly, but it can be instantiated by a class or struct that
implements an interface.
·
The class or struct that
implements an interface must provide an implementation for all the members that
are specified in the interface definition.
Difference between Abstract
Class and Interface
Abstract Class
|
Interface
|
In c#, the abstract classes cannot be instantiated
|
In c#, an interface cannot be instantiated directly, but
it can be instantiated by a class or struct that implements an interface.
|
By default, all the members of interface are public and we are not allowed to include any other access
modifiers.
|
|
A class can inherit multiple interfaces.
|
|
A class that is derived from abstract class must implement
all inherited abstract
methods and accessors.
|
By default, the members of interface
are public and we are not allowed to include any
other access
modifiers. In c#, an interface can contain a methods, properties,
events, indexers but it can’t contain constants, fields, operators,
instance constructors,
finalizers or types.
Events
In c#, event is a
message which is sent by an object to indicate that particular action is going to
be happen.
In simple words, we can
say that events are
used to signal an user actions such as button click, mouse over, menu
selection, etc. in user interface of windows and web applications.
Collections
In c#, collection is a class which is used to manage a group of
objects in flexible manner to perform a various operations like insert, update,
delete, get, etc. on object items in dynamic manner based on our requirements.
In previous section,
we learned about arrays in c# but those are useful only when we are working with fixed
number of strongly-typed objects. So, to solve this problem Microsoft has
introduced a collections in c# to work with group of objects which can grow or
shrink dynamically based on our requirements.
In c#, collection is a class so we must need to declare an instance
of the class before we perform any operations like add, delete, etc. on defined collection
and the collections are implemented by using IEnumerable interface so we can access collection
items by using foreach loop.
C# Collection Types
In c#, we have a
different type of collection classes are available, those are
·
Non-Generic (System.Collections)
·
Generic (System.Collections.Generic)
·
Concurrent (System.Collections.Generic)
C# Non-Generic Collections (System.Collections)
In c#, non-generic
collection classes are useful to store an elements of different data types and these are provided by System.Collections namespace. Now, these collection classes are legacy types so whenever
possible try to use generic collections (System.Collections.Generic) or concurrent collections (System.Collections.Concurrent).
Following are the
different type of non-generic collection classes which are provided by System.Collections namespace.
Class
|
Description
|
It is useful to represent an array of objects whose size
is dynamically increased as required.
|
|
It is useful to represent a FIFO (First in, First Out)
collection of objects.
|
|
It is useful to represent a LIFO (Last in, First Out)
collection of objects.
|
|
It is useful to represent a collection of key/value pairs
that are organized based on the hash code of the key.
|
C# Generic Collections
(System.Collections.Generic)
In c#, generic
collections will enforce a type safety so we can store only the elements which
is having same data type and these are provided by System.Collections.Generic namespace.
Following are the different
type of generic collection classes which are provided by System.Collections.Generic namespace.
Class
|
Description
|
It is useful to represent a list of objects that can be
accessed by index.
|
|
It is useful to represent a FIFO (First in, First Out)
collection of objects.
|
|
It is useful to represent a LIFO (Last in, First Out)
collection of objects.
|
|
It is useful to represent a collection of key/value pairs
that are sorted by a key.
|
|
It is useful to represent a collection of key/value pairs
that are organized based on the key.
|
C# Concurrent Collections (System.Collections.Concurrent)
In c#, concurrent
collections are useful to access a collection items from multiple threads and
these are available from .NET Framework 4 with System.Collections.Concurrent namespace.
In case, if we are
using a multiple threads to access a collection concurrently, then we need to
use concurrent collections instead of non-generic and generic collections.
Following are the
different type of concurrent collection classes which are provided by System.Collections.Concurrentnamespace.
Class
|
Description
|
BlockingCollection
|
It is useful to provide a blocking and bounding
capabilities for thread-safe collections.
|
ConcurrentBag
|
It is useful to represent a thread-safe, unordered
collection of objects.
|
ConcurrentDictionary<K,V>
|
It is useful to represent a thread-safe collection of
key/value pairs that can be accessed by multiple threads concurrently.
|
ConcurrentQueue
|
It is useful to represent a thread-safe FIFO (First in,
First Out) collection.
|
ConcurrentStack
|
It is useful to represent a thread-safe LIFO (Last in,
First Out) collection.
|
Partitioner
|
It is useful to provide a partitioning strategies for
arrays, lists, enumerables.
|
OrderablePartitioner
|
It is useful to provide a specific way of splitting an
orderable data source into multiple partitions.
|
Arraylist
Arraylist is
used to store an elements of different data types and
the size of arraylist can grow or shrink dynamically based on the need of our
application like adding or removing an elements from arraylist.
In
c#, arraylists are same as an arrays but
only difference is arrays are
used to store a fixed number of same data type elements.
C#
Arraylist Declaration
In
c#, arraylist is a non-generic type
of collection and it is provided by System.Collections namespace.
C# Arraylist Properties
Property
|
Description
|
Capacity
|
It is used to get or set the number of
elements an arraylist can contain.
|
Count
|
It is used to get the number of elements in
arraylist.
|
IsFixedSize
|
It is used to get a value to indicate that
the arraylist has fixed size or not.
|
IsReadOnly
|
It is used to get a value to indicate that
the arraylist is readonly or not.
|
Item
|
It is used get or set an element at the
specified index.
|
IsSynchronized
|
It is used to get a value to inidicate that
an access to arraylist is synchronized (thread safe) or not.
|
C# Arraylist Methods
Following are the some
of commonly used methods of
an arraylist to add, search, insert, delete or sort an elements of arraylist in
c# programming language.
Method
|
Description
|
Add
|
It is used to add an element at the end of
arraylist.
|
AddRange
|
It is used to add all the elements of
specified collection at the end of arraylist.
|
Clear
|
It will remove all the elements in
arraylist.
|
Clone
|
It will create a shallow copy of arraylist.
|
Contains
|
It is used determine whether the specified
element exists in arraylist or not.
|
CopyTo
|
It is used to copy all the elements of an
arraylist into another compatible array.
|
GetRange
|
It is used to return a specified range of
arraylist elements starting from the specified index.
|
IndexOf
|
It is used to search for a specified element
and return a zero-based index if found otherwise return -1 if no element
found.
|
Insert
|
It is used to insert an element in arraylist
at the specified index.
|
InsertRange
|
It is used to insert all the elements of
specified collection into arraylist starting from the specified index.
|
Remove
|
It is used to remove a first occurence of
specified element from the arraylist.
|
RemoveAt
|
It is used to remove an element from
arraylist based on the specified index position.
|
RemoveRange
|
It is used to remove a range of elements
from arraylist.
|
Reverse
|
It reverse the order of arraylist elements.
|
Sort
|
It sorts the elements in an arraylist.
|
ToArray
|
It copies all the elements of an arraylist
to new array object.
|
HashTable
In
c#, Hashtable is
used to store a collection of key/value pairs of different data types and
those are organized based on the hash code of the key.
Generally,
the hastable object will contain a buckets to store an elements of collection.
Here, bucket is a virtual subgroup of elements within the hashtable and each
bucket is associated with a hash code, which is generated based on the key of
element.
In
c#, hashtable is same as dictionary object
but only difference is the dictionary object
is used to store a key value pair of same data type elements.
When
compared with dictionary object,
the hashtable will provide a lower performance because the hashtable elements
are of object type so the boxing and unboxing process will occur when we store
or retrieve a values from hashtable.
Inheritance
In
c#, Inheritance is
a one of the primary concept of object oriented programming (OOP) and it is
used to inherit the properties from one class (base) to another (child) class.
The
inheritance will enable us to create a new class by
inheriting the properties from
other classes to
reuse, extend and modify the behaviour of other class members
based on our requirements.
In c#
inheritance, the class whose
members are inherited is called a base (parent) class and
the class that
inherits the members of base (parent) class is
called a derived (child) class.
Method
Overloading
In c#, Method Overloading means
defining a multiple methods with same name but with different parameters. By using Method Overloading,
we can perform a different tasks with same method name by passing different
parameters.
Method
Overriding
In
c#, Method
Overriding means override a base class method in
derived class by
creating a method with
same name and signatures to perform a different task. The Method Overriding in
c# can be achieved by using override & virtualkeywords
along with inheritance principle.
Suppose,
if we want to change the behaviour of base class method in
derived class,
then we need to use method
overriding. The base class method which
we want to override in derived class that
needs to be defined with virtualkeyword
and we need to use override keyword
in derived class while
defining the method with
same name and parameters then only we can override the base class method in
derived class.
In
c#, the Method Overriding is also called as run time polymorphism or late binding.
Polymorphism
In c#, polymorphism provides an ability for the classes to implement a different methods that are called through the same name and it also provides an ability to invoke the methods of derived class through base class reference during runtime based on our requirements.
C# Abstract Class Features
Following are
important features of abstract class in c# programming language.
- In c#, abstract classes cannot
be instantiated.
- The abstract classes can
contain both abstract and non-abstract methods and accessors.
- In c#, we should not use
a sealed keyword
with abstract class because the sealed keyword
will make a class as not inheritable but abstract modifier
requires a class to
be inherited.
- A class that is derived from
abstract class must include all the implementations of inherited abstract
methods and accessors.
C# Abstract Method
The abstract
class cannot be instantiated and it can contain both
abstract and non-abstract members. The class that is derived from abstract
class must implement all the inherited abstract methods and accessors.
In c#, abstract method is a method which
is declared with an abstract modifier. If we define a method
with abstractmodifier, then that method doesn’t contain any implementation
and method declaration simply ends with semicolon.
In c#, abstract methods
are internally treated as virtual methods so those methods needs to be overridden in
derived class and we should not static or virtual modifiers during abstract method declaration.
C#
Exception
In
c#, Exception is
an unexpected event or an error which may occur during execution of the program
and it will provide necessary information about the error which occurred in our
application.
Generally,
the exceptions are thrown by .NET framework CLR (Common Language Runtime) or by
the code in our program. Following is the example which will throw an exception
when we execute it in c#.



the try block will
contain the guarded code that may cause an exception so that if any errors
occurred in our code, then immediately the code execution will be moved
to catch block
to handle those exceptions.
In c#, the finally block will always come after
try
or catch
blocks
and the finally
block will always execute even if an
exception occurred or not and it is useful to clean up or dispose of unmanaged
objects based on the requirements.
In c#, throw is
a keyword and
it is useful to throw an exception manually during execution of the program and
we can handle those thrown exceptions using try-catch blocks
based on our requirements.
C# Var Keyword Overview
Following are the
important points which we need to remember about var keyword in
c#.
- var keyword
is useful to declare the implicitly-typed local variables without specifying an explicit type.
- In c#, the type of
implicitly-typed local variables will automatically determine by the compiler
based on the right side value of the initialization statement.
- The var variables must be declared and initialized in the same
statement.
- We are not allowed to assign
a null value to the implicitly-typed local variables.
- Multiple implicitly-typed
variables cannot be initialized in the same statement.
- var is
not allowed to use as a field type at the class level.
C# Dynamic Type Overview
Following are the
important points which we need to remember about dynamic type in c#.
- The dynamic type
is useful to bypass the type checking at compile-time instead, it will
resolve the type at runtime.
- During compile-time, the
compiler will compile the variables of dynamic type into the variables of the objecttype.
- If we use dynamic type
as a method parameter, then it will accept any type of parameter at run
time.
- Visual studio will not provide
any IntelliSense support for dynamic types.
C# Nullable Types Characteristics
Following are the
important characteristics of the nullable type in c#.
- Nullable types are useful to
assign a null value to the value type variables.
- Nullable types can be declared
like either Nullable<T> or T?. The syntax T? is shorthand for Nullable<T> and these two are interchangeable.
- We can assign a value to
nullable type like int? i = 10 or Nullable<int>
i = 10 or int? i = null.
- By using nullable type HasValue and Value properties, we can verify and retrieve the
variable value like if(i.HasValue) j =
i.Value;.
- The HasValue property
will return true if the variable contains a value, or false if it is null and the Value property will return value if the variable
contains a value otherwise it will throw InvalidOperationException exception.
- We can use GetValueOrDefault() method to get the value from nullable type. It
will return the value of nullable type if it contains a value or if it
is null, then it will return the default value.
- To assign nullable type to
non-nullable type, then we need to use the null-coalescing operator ??.
- Nested nullable types are not
allowed like Nullable<Nullable<int>>
x.
C# Anonymous Type Overview
Following are the
important points which we need to remember about anonymous type in c#.
- In c#, anonymous types are useful to create an object that contains a
set of read-only properties without specifying its type using the new keyword.
- In an anonymous type, the
expression that is used to initialize a property cannot be null.
- The reference of anonymous
types can be held by implicitly typed variable var.
- The access scope of the
anonymous type is limited to the method where it has defined.
- In c#, anonymous types are
mostly useful in Select clause
of LINQ query expressions.
In c#, anonymous methods are
the methods without
a name. Generally, the anonymous methods can be defined by using delegate keyword and
can be assigned to the variable of
the delegate type.
C# Anonymous Methods Drawbacks
Following are some of
the limitations of anonymous methods in c#.
- In c#, we are not allowed to
use jump statements such as goto, break and continue inside of an anonymous method.
- Anonymous methods cannot access
ref or out parameters of an outer scope.
- The unsafe code cannot be
accessed within the anonymous method.
- Anonymous methods are not
allowed on the left side of is operator.
Actually, the
anonymous methods are introduced in C# 2.0 to create methods without a name but in C# 3.0 and later
versions, the lambda
expressions have been
introduced to achieve the better functionality than anonymous methods by
writing inline code. To learn more about lambda expressions, check LINQ Lambda Expressions.
C# Anonymous Methods Overview
Following are the
important points which we need to remember about the anonymous methods in c#.
- Anonymous methods are the methods without
a name.
- Anonymous methods can be
defined by using delegate keyword and
can be assigned to the variable of the delegate type.
- Anonymous methods are useful to
reduce the coding overhead in instantiating delegates because we don’t have to create a separate method.
- In anonymous methods, if we
define any parameters those can be accessed only within the anonymous
method block.
- We can pass anonymous methods
as a parameter to the other methods.
C# Indexer Overview
Following are the
important points which we need to remember about indexers in c#.
- In c#, indexer is a special
type of property and that allows an instances of a class or structure to be indexed same like an array.
- In c#, indexer is same as property but the only difference is, the indexer will
define with this keyword
along with the square bracket and parameters.
- Indexers can be overloaded by
having different signatures.
- Indexers cannot be a static member
as it’s an instance member of the class.
- Passing indexer value as
a ref or out parameter
not supported.
Extension
Methods
In c#, extension methods are
useful to extend the behaviour of existing types by adding new methods without
modifying, deriving or recompiling the original types such as class, struct or interface.
·
In c#, we can implement our own extension methods for any .NET
type such as custom class, .NET framework class or third party classes.
·
·
To create an extension method, we need to define a static
class and implement an extension method as a static
methodwith the required parameters. The first parameter of the method will
specify the type on which the extension method will operate on and it must be
preceded by this modifier.
C# Extension Methods Overview
Following are the
important points which we need to remember about extension methods in c#.
- Extension methods are useful to
extend the behaviour of existing types without modifying, deriving or
recompiling the original types.
- We can create an extension
method for any .NET type such as custom class, .NET framework class or
third party classes.
- In c#, the extension methods
will be defined as static methods of a static class with required parameters.
- The first parameter of the
extension method will specify the type on which the method will
operate on and it must be preceded by this modifier.
- The extension methods can be
used anywhere in our application by including the namespace of our
extension method.
- In c#, the extension methods
can be accessed like an instance method of extended type.
In
c#, thread is
a basic unit of execution within the process and it is responsible for
executing the application logic.
By default, every
application or program will carry one thread to execute the application logic
and that thread is called a Main
thread. So, we can say that every program or application is by default
a single threaded model.
C# Thread Life Cycle
In c#, each thread
will have a life cycle and it will start when we create an instance of object
using Thread class. Once the task execution of thread is completed,
then the life cycle of thread will get end.
At any point of time,
the thread in c# will exists in any one of the following states.
State
|
Description
|
Unstarted
|
When we create the thread that will be in
unstarted state.
|
Runnable
|
When we call the Start() method, the thread
will be moved to ready to run or runnable state.
|
Running
|
It indicates that the thread is in running
state.
|
Not Runnable
|
If thread is in not runnable state means
there is a chance that the Sleep() or Wait() or Suspend() method is called on
the thread or blocked by I/O operations.
|
Dead
|
If thread is in dead state means the thread
completes its task execution or it is aborted.
|
C# Thread Overview
Following are the
important points which we need to remember about threads in c#.
- In c#, the thread is a basic unit of execution within the process
and it is responsible for executing the application logic.
- By default, every program will
carry one thread to execute the program logic and that thread is called
the Main
thread.
- In c#, to work with threads we
need to import System.Threading namespace in our program.
- After importing System.Threading namespace in our program, we can create or access the
threads using Threadclass.
- In c#, the Main thread will automatically create to handle the
program logic. If we create any other threads in our program by
using Thread class those will become a child threads for the Main thread.
- In c#, each thread will have a
life cycle and it will start when we create an instance of the object
using Thread class.
- In c#, by using Abort() method of Thread class we can end or abort the thread execution
process.
- In c#, two types of threads are
available, those are foreground threads and background threads.
- Foreground threads are the threads
which will run until it finishes its work even if, the Main thread completes its process.
- Background threads will quit
its process immediately when Main thread
quits.
In c#, multithreading means
executing the multiple threads simultaneously to perform multiple tasks at a
time.
To
overcome this problem, multithreading has
been introduced to execute the multiple tasks simultaneously (asynchronous way)
by creating multiple threads in our application. The threads which
we will create in our application will become a child threads for the Main
thread.
In
c#, the child threads are responsible for executing the tasks in an asynchronous way
that means executing the multiple tasks simultaneously at a time.
To
overcome this problem, multithreading has
been introduced to execute the multiple tasks simultaneously (asynchronous way)
by creating multiple threads in our application. The threads which
we will create in our application will become a child threads for the Main
thread.
In
c#, the child threads are responsible for executing the tasks in an asynchronous way
that means executing the multiple tasks simultaneously at a time.
In c#, sleep method
is useful to suspend or pause the current thread execution for the specified amount of time.
Tuple
In c#, Tuple is
a data structure and it is useful to store the sequence of elements of
different data
types. By using tuple we can return more than one
value from the methods as a single set of data.
In
c#, ValueTuple is
same as Tuple to
store the sequence of elements of different data types but
the only difference is ValueTuples are
the value types (structures)
rather than reference
types (classes)
like Tuple and
it will overcome the limitations of Tuple class.
The ValueTuple has
been introduced in C# 7.0 (.NET Framework 4.7) and it will available in your
project if you are using .NET Framework 4.7 or higher, or .NET Standard 2.0 or
higher.
No comments:
Post a Comment