C# BASICS
LESSON 1
TOPICS
Basic Data Types
Classes
Namespaces
Interfaces
Managing Errors with Exceptions
Casting
Structures
Enumerations
BASIC DATA TYPES
C# DATA TYPES
A variable in C# must be a specified data type:
C# DATA TYPES
A data type specifies the size and type of variable values.
It is important to use the correct data type for the corresponding variable; to avoid errors, to save time and
memory, but it will also make your code more maintainable and readable. The most common data types are:
NUMBERS
Number types are divided into two groups:
Integer types stores whole numbers, positive or negative (such as 123 or -456), without decimals.Valid types are
int and long. Which type you should use, depends on the numeric value.
Floating point types represents numbers with a fractional part, containing one or more decimals. Valid types are
float and double.
INTEGER TYPES
The int data type can store whole numbers from -2147483648 to 2147483647. In general, and in our tutorial, the
int data type is the preferred data type when we create variables with a numeric value
The long data type can store whole numbers from -9223372036854775808 to 9223372036854775807. This is
used when int is not large enough to store the value. Note that you should end the value with an "L":
FLOATING POINT TYPES
You should use a floating point type whenever you need a number with a decimal, such as 9.99 or 3.14515.
The float and double data types can store fractional numbers. Note that you should end the value with an "F" for
floats and "D" for doubles:
FLOATING POINT TYPES
A floating point number can also be a scientific number with an "e" to indicate the power of 10:
BOOLEANS
A boolean data type is declared with the bool keyword and can only take the values true or false:
CHARACTERS
The char data type is used to store a single character. The character must be surrounded by single quotes, like 'A'
or 'c':
STRINGS
The string data type is used to store a sequence of characters (text). String values must be surrounded by double
quotes:
CLASSES
C# CLASS AND OBJECTS
A class is like a blueprint of a specific object that has certain attributes and features. For example, a car should
have some attributes such as four wheels, two or more doors, steering, a windshield, etc. It should also have some
functionalities like start, stop, run, move, etc. Now, any object that has these attributes and functionalities is a car.
Here, the car is a class that defines some specific attributes and functionalities. Each individual car is an object of
the car class. You can say that the car you are having is an object of the car class.
Likewise, in object-oriented programming, a class defines some properties, fields, events, methods, etc. A class
defines the kinds of data and the functionality their objects will have.
DEFINE A CLASS
In C#, a class can be defined by using the class keyword. Let's define a class named 'Student'.
A class can contain one or more constructors, fields, methods, properties, delegates, and events. They are called
class members. A class and its members can have access modifiers such as public, private, protected, and internal,
to restrict access from other parts of the program.
FIELD
A class can have one or more fields. It is a class-level variable that holds a value. Generally, field members should
have a private access modifier used with property.
PROPERTY
A property encapsulates a private field using setter and getter to assign
and retrieve underlying field value.
In the right example, the id is a private field that cannot be accessed
directly. It will only be accessed using the StudentId property. The get{ }
returns the value of the underlying field and set{ } assigns the value to
the underlying field id.
AUTO-IMPLEMENTED PROPERTY
From C# 3.0 onwards, property declaration has been made easy if you don't want to apply some logic in getter
or setter. Using auto-implemented property, you don't need to declare an underlying private field. C# compiler
will automatically create it in IL code.
In the above example, backing private field for the FirstName and LastName will be created internally by the
compiler. This speed up the development time and code readability.
METHOD
A method can contain one or more statements to be executed as a single unit. A method may or may not return
a value. A method can have one or more input parameters.
The following defines the Sum method that returns the sum of two numbers.
METHOD
The following method doesn't return anything and doesn't have any parameters. The return type is void.
METHOD
The following defines the GetFullName() method in the Student class.
CONSTRUCTOR
A constructor is a special type of method which will be called
automatically when you create an instance of a class. A constructor is
defined by using an access modifier and class name <access-modifier>
<class-name>(){ }.
A constructor name must be the same as a class name.
A constructor can be public, private, or protected.
The constructor cannot return any value so cannot have a return type.
A class can have multiple constructors with different parameters but can
only have one parameterless constructor.
If no constructor is defined, the C# compiler would create it internally.
OBJECTS OF A CLASS
You can create one or more objects of a class. Each object can have different values of properties and field but
methods and events behaves the same.
In C#, an object of a class can be created using the new keyword and assign that object to a variable of a class
type. For example, the following creates an object of the Student class and assign it to a variable of the Student
type.
OBJECTS OF A CLASS
You can now access public members of a class using the object.MemberName notation.
OBJECTS OF A CLASS
You can create multiple objects of a class with different values of properties and fields.
NAMESPACES
C# NAMESPACE
Namespaces play an important role in managing related
classes in C#.The .NET Framework uses namespaces to
organize its built-in classes. For example, there are some
built-in namespaces in .NET such as System, System.Linq,
System.Web, etc. Each namespace contains related classes.
A namespace is a container for classes and namespaces. The
namespace also gives unique names to its classes thereby you
can have the same class name in different namespaces.
In C#, a namespace can be defined using the namespace
keyword.
C# NAMESPACE
The following namespace contains the Student and Course classes.
C# NAMESPACE
Classes under the same
namespace can be referred to as
namespace.classname syntax. For
example, the Student class can be
accessed as School.Student.
C# NAMESPACE
To use classes under a namespace without
the fully qualified name, import the
namespace with the using keyword at the top
of C# class file.
C# NAMESPACE
A namespace can contain other namespaces. Inner
namespaces can be separated using (.).
In the right example, the fully qualified class name is
School.Education.Student.
C# NAMESPACE
Beginning with C# 10, you can declare a namespace
for all types defined in that file without wrapping
classes inside curly braces { .. }, as shown below.
INTERFACES
C# - INTERFACE
In the human world, a contract between the two or more humans binds them to act as per the contract. In the
same way, an interface includes the declarations of related functionalities. The entities that implement the
interface must provide the implementation of declared functionalities.
In C#, an interface can be defined using the interface keyword. An interface can contain declarations of methods,
properties, indexers, and events. However, it cannot contain instance fields.
C# - INTERFACE
The following interface declares some basic functionalities for the file operations.
The above declares an interface named IFile. (It is recommended to start an interface name with the letter "I" at
the beginning of an interface so that it is easy to know that this is an interface and not a class.) The IFile interface
contains two methods, ReadFile() and WriteFile(string).
C# - INTERFACE
IMPLEMENTING AN INTERFACE
A class or a Struct can implement one or more
interfaces using colon :. On impmenting an
interface, you must override all the members of
an interface.
IMPLEMENTING AN INTERFACE
For example, the following FileInfo class implements the IFile
interface, so it should override all the members of IFile.
In the above example, the FileInfo class implements the IFile
interface. It overrides all the members of the IFile interface with
public access modifier. The FileInfo class can also contain
members other than interface members.
IMPLEMENTING AN INTERFACE
At the right, we created objects of the FileInfo class and assign it to
IFile type variable and FileInfo type variable. When interface
implemented implicitly, you can access IFile members with the IFile
type variables as well as FileInfo type variable.
EXPLICIT IMPLEMENTATION
An interface can be implemented explicitly using
<InterfaceName>.<MemberName>. Explicit implementation is
useful when class is implementing multiple interfaces; thereby, it
is more readable and eliminates the confusion. It is also useful if
interfaces have the same method name coincidently.
EXPLICIT IMPLEMENTATION
When you implement an interface explicitly, you can access
interface members only through the instance of an interface
type.
In the right example, file1 object can only access members of
IFile, and file2 can only access members of FileInfo class. This is
the limitation of explicit implementation.
IMPLEMENTING MULTIPLE
INTERFACES
A class or struct can implement
multiple interfaces. It must
provide the implementation of
all the members of all interfaces.
At the right, the FileInfo
implements two interfaces IFile
and IBinaryFile explicitly. It is
recommended to implement
interfaces explicitly when
implementing multiple interfaces
to avoid confusion and more
readability.
DEFAULT INTERFACE METHODS
Till now, we learned that interface can
contain method declarations only. C#
8.0 added support for virtual extension
methods in interface with concrete
implementations.
The virtual interface methods are also
called default interface methods that do
not need to be implemented in a class
or struct.
In the right IFile interface, the
DisplayName() is the default method.
The implementation will remain same
for all the classes that implements the
IFile interface. Note that a class does
not inherit default methods from its
interfaces; so, you cannot access it using
the class instance.
MODIFIERS IN INTERFACES
C# 8.0 allows private, protected, internal, public, virtual, abstract, sealed, static, extern, and partial modifiers in an
interface.
The default access level for all interface members is public.
An interface member whose declaration includes a body is a virtual member unless the sealed or private
modifier is used.
A private or sealed function member of an interface must have implementation body.
Interfaces may declare static members which can be accessed by interface name.
MANAGING ERRORS WITH EXCEPTION
EXCEPTION HANDLING IN C#
Here, you will learn about exception handling in C# using try, catch, and finally blocks.
Exceptions in the application must be handled to prevent crashing of the program and unexpected result, log
exceptions and continue with other functionalities. C# provides built-in support to handle the exception using try,
catch & finally blocks.
EXCEPTION HANDLING IN C#
try block: Any suspected code that may raise
exceptions should be put inside a try{ } block. During
the execution, if an exception occurs, the flow of the
control jumps to the first matching catch block.
catch block: The catch block is an exception handler
block where you can perform some action such as
logging and auditing an exception.The catch block
takes a parameter of an exception type using which
you can get the details of an exception.
finally block: The finally block will always be executed
whether an exception raised or not. Usually, a finally
block should be used to release resources, e.g., to
close any stream or file objects that were opened in
the try block.
EXCEPTION HANDLING IN C#
The following may throw an exception if you enter a non-numeric character.
EXCEPTION HANDLING IN C#
To handle the possible exceptions in the above
example, wrap the code inside a try block and handle
the exception in the catch block, as shown below.
In the above example, we wrapped this code inside a
try block. If an exception occurs inside a try block,
then the program will jump to the catch block. Inside
a catch block, we display a message to instruct the
user about his mistake, and in the finally block, we
display a message about what to do after running a
program.
EXCEPTION HANDLING IN C#
Ideally, a catch block should include a parameter of a built-
in or custom exception class to get an error detail. The
following includes the Exception type parameter that
catches all types of exceptions.
EXCEPTION FILTERS
You can use multiple catch blocks with the different
exception type parameters. This is called exception filters.
Exception filters are useful when you want to handle
different types of exceptions in different ways.
In the right example, we have specified multiple catch blocks
with different exception types. We can display an appropriate
message to the user, depending upon the error, so the user
does not repeat the same mistake again.
INVALID CATCH BLOCK
A parameterless catch block and a
catch block with the Exception
parameter are not allowed in the
same try-catch statements, because
they both do the same thing.
INVALID CATCH BLOCK
Also, parameterless catch block catch{ } or general catch
block catch(Exception ex){ } must be the last block. The
compiler will give an error if you have other catch blocks
after a catch{ } or catch(Exception ex) block.
FINALLY BLOCK
The finally block is an optional block and
should come after a try or catch block. The
finally block will always be executed whether
or not an exception occurred. The finally block
generally used for cleaning-up code e.g.,
disposing of unmanaged objects.
NESTED TRY-CATCH
C# allows nested try-catch blocks. When using nested try-
catch blocks, an exception will be caught in the first
matching catch block that follows the try block where an
exception occurred.
An inner catch block will be executed in the right example
because it is the first catch block that handles all exception
types.
NESTED TRY-CATCH
If there isn't an inner catch block that matches with raised exception
type, then the control will flow to the outer catch block until it finds
an appropriate exception filter. Consider the following example.
In the right example, an exception of type DivideByZeroException
will be raised. Because an inner catch block handles only the
NullReferenceTypeException, it will be handle by an outer catch
block.
CASTING
C# TYPE CASTING
Type casting is when you assign a value of one data type to another type.
In C#, there are two types of casting:
IMPLICIT CASTING
Implicit casting is done automatically when passing a smaller size type to a larger size type:
EXPLICIT CASTING
Explicit casting must be done manually by placing the type in parentheses in front of the value:
TYPE CONVERSION METHODS
It is also possible to convert data types explicitly by using built-in methods, such as Convert.ToBoolean,
Convert.ToDouble, Convert.ToString, Convert.ToInt32 (int) and Convert.ToInt64 (long):
STRUCTURES
C# - STRUCT
In C#, struct is the value type data type that represents data structures. It can contain a parameterized
constructor, static constructor, constants, fields, methods, properties, indexers, operators, events, and nested
types.
struct can be used to hold small data values that do not require inheritance, e.g. coordinate points, key-value pairs,
and complex data structure.
STRUCTURE DECLARATION
A structure is declared using struct keyword. The
default modifier is internal for the struct and its
members.
The following example declares a structure
Coordinate for the graph.
STRUCTURE DECLARATION
A struct object can be created with or without
the new operator, same as primitive type
variables.
At the right, an object of the Coordinate
structure is created using the new keyword. It
calls the default parameterless constructor of the
struct, which initializes all the members to their
default value of the specified data type.
STRUCTURE DECLARATION
If you declare a variable of struct type without
using new keyword, it does not call any
constructor, so all the members remain
unassigned. Therefore, you must assign values
to each member before accessing them,
otherwise, it will give a compile-time error.
CONSTRUCTORS IN
STRUCTURE
A struct cannot contain a parameterless
constructor. It can only contain
parameterized constructors or a static
constructor.
You must include all the members of the
struct in the parameterized constructor
and assign parameters to members;
otherwise C# compiler will give a
compile-time error if any member
remains unassigned.
METHODS AND PROPERTIES IN STRUCTURE
A struct can contain properties, auto-implemented
properties, methods, etc., same as classes.
METHODS AND PROPERTIES
IN STRUCTURE
The following struct includes the static method.
EVENTS IN STRUCTURE
A struct can contain events to notify subscribers about some
action. The following struct contains an event.
The right structure contains CoordinatesChanged event, which will
be raised when x or y coordinate changes. The following example
demonstrates the handling of the CoordinatesChanged event.
EVENTS IN STRUCTURE
struct is a value type, so it is faster than a
class object. Use struct whenever you want to
just store the data. Generally, structs are good
for game programming. However, it is easier
to transfer a class object than a struct. So do
not use struct when you are passing data
across the wire or to other classes.
SUMMARY
ENUMERATIONS
C# ENUMERATIONS TYPE - ENUM
In C#, an enum (or enumeration type) is used to assign constant names to a group of numeric integer values. It
makes constant values more readable, for example, WeekDays.Monday is more readable then number 0 when
referring to the day in a week.
An enum is defined using the enum keyword, directly inside a namespace, class, or structure. All the constant
names can be declared inside the curly brackets and separated by a comma. The following defines an enum for the
weekdays.
C# ENUMERATIONS TYPE - ENUM
At the right, the WeekDays enum declares members in each
line separated by a comma.
ENUM VALUES
If values are not assigned to enum members, then the
compiler will assign integer values to each member
starting with zero by default. The first member of an enum
will be 0, and the value of each successive enum member is
increased by 1.
ENUM VALUES
You can assign different values to enum member. A change
in the default value of an enum member will automatically
assign incremental values to the other members
sequentially.
ENUM VALUES
You can even assign different values to each member.
ENUM VALUES
The enum can be of any numeric data type such as byte, sbyte,
short, ushort, int, uint, long, or ulong. However, an enum
cannot be a string type.
Specify the type after enum name as : type. The following
defines the byte enum.
ACCESS AN ENUM
An enum can be accessed using the dot syntax:
enum.member
CONVERSION
Explicit casting is required to
convert from an enum type to its
underlying integral type.
THANK YOU
This Photo by Unknown author is licensed under CC BY-SA-NC.