In C#, DirectoryInfo Class is a part of System.IO namespace and it provides properties and methods to perform various operations on directory and subdirectory such as to create, delete and move directory. It cannot be inherited.
C# DirectoryInfo Properties
The following tables list the properties provided by DirectoryInfo class.
Property
Description
CreationTime
It is used to get or set the creation time of the current file or directory.
Exists
This property provides a value indicating whether the directory exists or not.
Extension
It is used to get the extension part of the file.
Name
It is used to get the name of this DirectoryInfo instance.
FullName
This property provides the full path of a directory.
LastAccessTime
It is used to gets or sets the time the current file or directory was last accessed.
Parent
It is useful to get the parent directory of a specified subdirectory.
C# DirectoryInfo Methods
Method
Description
Create()
It creates a directory.
Delete()
It deletes the specified directory.
EnumerateDirectories()
It returns an enumerable collection of directory information in the current directory.
GetDirectories()
Returns the subdirectories of the current directory.
GetFiles()
Returns the file list from the current directory.
MoveTo()
It moves a specified directory and its contents to a new path.
ToString()
It returns the original path that was passed by the user.
Example: C# program for DirectoryInfo Class
The program is used to create a directory in C#.
using System;
using System.IO;
namespace FileExample
{
class Program
{
static void Main(string[] args)
{
string fLoc = "Sample";
DirectoryInfo dir = new DirectoryInfo(fLoc);
// checking for its existence
if (dir.Exists)
{
Console.WriteLine("The Directory already exists.");
}
else
{
// creating directory
dir.Create();
Console.WriteLine("Directory Created Successfully!");
}
}
}
}
Output:
Directory Created Successfully!
A directory named “Sample” will be created on a path that you will specify in a program. The program also checks if the directory specified already exists in that path or not.
Example: C# program for DirectoryInfo Class tp delete a directory
using System;
using System.IO;
namespace FileExample
{
class Program
{
static void Main(string[] args)
{
string fLoc = "sample.text";
DirectoryInfo dir = new DirectoryInfo(fLoc);
try
{
dir.Delete();
Console.WriteLine("Directory Deleted Successfully!");
}
catch (Exception ex)
{
Console.WriteLine("Something is wrong: " + ex.ToString());
}
}
}
}
In C#, FileInfo class provides properties and instance methods that are used to deal with the various operations in a file such as creating, copying, deleting, moving, etc.
It is derived from FileSystemInfo class and is a part of System.IO namespace.
C# FileInfo Properties
The following are some of the most used properties in FileInfo class.
Property
Description
Directory
It returns an instance of the parent directory of a file.
DirectoryName
It retrieves the directory full path as a string.
Exists
It returns a value that indicates whether the file exists or not.
IsReadOnly
It is used to get or set a value that determines whether the current file is read-only or not.
Length
This property gets the size of the current file in bytes.
Name
It is used to get the name of the file.
Extension
This will return an extension part of the file.
CreationTime
It is used to get or set the creation time of the current file or directory.
LastAccessTime
It is used to get or set the last access time of the current file or directory.
LastWriteTime
It is used to get or set the time when the current file or directory was last written to.
C# FileInfo Methods
The table below lists the methods used in FileInfo class.
Method
Description
Create()
This method is used to create a file.
CopyTo(String)
This method copies an existing file to a new file, but it won’t allow overwriting an existing file.
CopyTo(String, Boolean)
This method will copy an existing file to a new file, allowing overwriting an existing file.
CreateText()
It creates a StreamWriter that writes a new text file.
AppendText()
It creates a StreamWriter that appends text to the file.
Encrypt()
This method is useful to encrypt a file so that only the account used to encrypt the file can decrypt it.
Decrypt()
This method is useful to decrypt a file that is encrypted by the current account using the encrypt method.
Delete()
It deletes the file permanently.
Open()
This method opens a file in the specified mode.
OpenRead()
This method creates a read-only file stream.
OpenWrite()
This method creates a write-only file stream.
OpenText()
This method creates a stream reader that reads from an existing text file.
Replace()
This method is used to replace the contents of the specified file with the file described by the current fileinfo object.
ToString()
It returns the path as a string.
Now, let us go through an example in C# for FileInfo.
Example: C# FileInfo program for creating a file
using System;
using System.IO;
namespace FileProgram
{
class Program
{
static void Main(string[] args)
{
string fLoc = "sample.text";
// Check file if exists
if (File.Exists(fLoc))
{
File.Delete(fLoc);
}
FileInfo f = new FileInfo(fLoc);
f.Create();
Console.WriteLine("File is created Successfuly");
}
}
}
Output: After execution, you will see the following result.
File is created Successfuly
Also, since we created a new file, a file name “sample.text” will be created in the same path where you have saved your code file. Although, if you want to change the directory of the newly created file then you can give the full pathname instead of just the file name.
Example: C# FileInfo program to Write and Read from a file
using System;
using System.IO;
namespace FileProgram
{
class Program
{
static void Main(string[] args)
{
string fLoc = "sample.text";
// Check file if exists
if (File.Exists(fLoc))
{
File.Delete(fLoc); //if file exists then delete that file
}
FileInfo f = new FileInfo(fLoc);
// Writing to the file
StreamWriter sw = f.CreateText();
sw.WriteLine("Hi! Welcome to Simple2code.com.");
sw.Close();
// Reading from a file
StreamReader sr = f.OpenText();
string text = "";
while ((text = sr.ReadLine()) != null)
{
Console.WriteLine(text);
}
}
}
}
Output: After execution, you will see the following result.
Hi! Welcome to Simple2code.com.
A file will be created and the above text is written on it. The program first writes the string on a text file and then reads from it.
BinaryReader and BinaryWriter are the classes that are used to read and write into a binary file. These are just like C# StreamReader and StreamWriter except here we read and write to a binary file.
C# BinaryReader class
This class in C# is used to read binary information from a file. This class is present in System.IO namespace.
The BinaryReader contains the following commonly used methods.
Methods
Description
Close()
This method closes the BinaryReader object and the resources associated with it.
Read()
It reads the character from the stream and increments the position of the stream.
ReadBoolean()
It is used to read the boolean value and increases the stream by one byte.
ReadString()
It is used to read a string from the current stream. The string is prefixed with the length, encoded as an integer seven bits at a time.
C# BinaryWriter Class
The BinaryWriter class is used to write binary information into a stream. This class is present in System.IO namespace.
The BinaryWriter contains the following commonly used methods.
Methods
Description
Close()
This method closes the BinaryReader object and the resources associated with it.
Write(type value)
It is used to write on the current stream. we place the type and value according to the need. Write(bool value) , Write(byte value) , Write(char ch), Write(double value) , Write(int value) , Write(string value)
Flush()
It is used to clear all buffers on the current writer and causes any buffered data to be written to the underlying device.
Seek(int offset, SeekOrigin origin)
It is used to set a position on a current stream in a file.
Example: C# program for BinaryReader and BinaryWriter classes
using System;
using System.IO;
namespace FileProgram
{
class Program
{
static void Main(string[] args)
{
//BinaryWriter
BinaryWriter bw = new BinaryWriter(new FileStream("sample.dat", FileMode.Create));
bw.Write("This is Simple2code.com.");
bw.Write(23.123);
bw.Write(true);
bw.Write(45);
bw.Close();
//BinaryReader
BinaryReader br = new BinaryReader(new FileStream("sample.dat", FileMode.Open));
Console.WriteLine("String : " + br.ReadString());
Console.WriteLine("Double : " + br.ReadDouble());
Console.WriteLine("Boolean : " + br.ReadBoolean());
Console.WriteLine("Integer : " + br.ReadInt32());
br.Close();
}
}
}
Output: After the execution of the above program a new file sample.dat file will be created and the information written on it will be displayed on the screen.
String : This is Simple2code.com. Double : 23.123 Boolean : True Integer : 45
The StreamReader class inherits from TExtReader class. It is used for reading data from a file. The most used method in this class are:
Close(): It closes the Streamreader object or any resources assosciateed with it.
Peek(): It returns the next available character but does not consume it.
Read(): It reads the next characer in input stream and increases the charcter position by one.
ReadLine(): It reads the line from input stream and returns the data in the form of string.
Seek(): This method is used to read or write the data at a specific location from a file.
Example: C# program for StreamReader
Let us create a file called sample.text for this example and the following string is present there:
This is a Website. This is Simple2code.com. Visit again.
using System;
using System.IO;
namespace FileProgram
{
class Program
{
static void Main(string[] args)
{
StreamReader sr = new StreamReader("sample.txt");
string str = sr.ReadLine();
while (str != null)
{
Console.WriteLine(str);
str = sr.ReadLine();
}
sr.Close();
}
}
}
Output: The string present in a sample.text will be displayed on the screen.
This is a Website. This is Simple2code.com. Visit again.
C# StreamWriter Class
StreamWriter class inherits TextWriter class. it is used to write a series of characters to a stream in a particular format. The most used method in this class are:
Close(): This methosd closes the current StreamWriter object and all the resources assosciated with it.
Flush(): It clears all the data from the buffer and write it in the stream associate with it.
Write(): It is used to write data to a stream.
WriteLine(): It writes the the data to a stream and adds the newline character at the end of the data.
Example: C# program for StreamWriter
The following program creates a new file and writes data into that file. The data is provided in the program.
using System;
using System.IO;
namespace FileProgram
{
public class Program
{
public static void Main(string[] args)
{
FileStream file = new FileStream("sample.txt", FileMode.Create);
StreamWriter sw = new StreamWriter(file);
sw.WriteLine("This is Simple2code.com. Visit again.");
sw.Close();
file.Close();
Console.WriteLine("The file is created.");
}
}
}
Output:
The file is created.
After execution, open the newly created file “sample.text”, you will find the following data.
Files are used to store the data permanently in the storage device with a specific name and path. And when we open the file in order to read or write, it becomes a stream.
File Handling refers to the various operation that can be performed on a file such as reading from a file, writing to a file, appending file, etc. The two most common operations are reading from a file and writing to a file. And when we open a file to do so then the file becomes a stream.
The System.IO namespace class contains the input and output streams handling classes that are used for performing the various operation.
The members that are included in System.IO namespace classes are:
I/OClass
Description
BinaryReader
Reads primitive data from a binary stream.
BinaryWriter
Writes primitive data in binary format.
BufferedStream
Temporary storage for a stream of bytes.
Directory
Helps in manipulating a directory structure.
DirectoryInfo
Used for performing operations on directories.
DriveInfo
Provides information for the drives.
File
Helps in manipulating files.
FileInfo
Used for performing operations on files.
FileStream
Used to read from and write to any location in a file.
MemoryStream
Used for random access to streamed data stored in memory.
Path
Performs operations on path information.
StreamReader
Used for reading characters from a byte stream.
StreamWriter
Is used for writing characters to a stream.
StringReader
Is used for reading from a string buffer.
StringWriter
Is used for writing into a string buffer.
C# FileStream
As already discussed above, FileStream class provides a stream for the various file operations. Reading and writing data into a file becomes easy with FileStream.
However, a FileStream object is required in order to create a new file or open an existing one. To create a FileStream object we use a new keyword in the following way.
Let us see what each of the above Enumerator means:
FileMode:
This emulator defines the various ways through which we can open a file and its member are:
Parameters
Description
Append
It creates a new file or opens a file(if exists any) and puts the cursor at the end of the file.
Create
It is used to create a new file.
CreateNew
This member specifies the OS that it should create a new file.
Open
It is used to open an existing file.
OpenOrCreate
It is used to open an existing file, if not then create a new one.
Truncate
It opens an existing file and truncates its size to zero bytes.
FileAccess:
This enumerator has three members:
Read: Only to read.
ReadWrite: Both read and write
Write: Only write.
FileShare:
FileShare refers to sharing of files and its members are:
Parameters
Description
Inheritable
It allows a filehandle to pass an inheritance to the child processes
None
Sharing of the current file is declined by this member.
Read
It opens a file only for reading.
ReadWrite
It opens a file for both reading and writing
Write
It opens a file only for writing.
Let us g through an example to see it in action.
Example: C# program for FileStream
The following program writes multiple bytes into the file
using System;
using System.IO;
namespace FileProgram
{
class Program
{
static void Main(string[] args)
{
FileStream f = new FileStream("sample.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
for (int i = 97; i <= 122; i++)
{
f.WriteByte((byte) i);
}
f.Close();
}
}
}
Output: Once the program is executed, a new file will be created if it doesn’t already exist. And inside that file, the following text will be present.
We have already discussed the exception handling in C# and how to handle the exception if one exists. The exception discussed are raised by the CLR automatically, now we will see how we can manually raise an exception.
In C#, we use the keyword ‘throw’ in order to throw an exception programmatically. We can raise any type of exception derived from the Exception class with the help of the throw keyword.
The syntax for throw keyword.
throw e;
In this syntax e is an exception that is derived from the Exception class.
Example: C# program for throw keyword
using System;
namespace ExceptionEg
{
class Employee
{
static void Main(string[] args)
{
try
{
empDetails();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
// static method
private static void empDetails()
{
string emp_name = null;
if (string.IsNullOrEmpty(emp_name))
{
throw new NullReferenceException("Employee name is Empty");
}
else
{
Console.WriteLine("Employee Name: " + emp_name);
}
}
}
}
Output:
Employee name is Empty
As you can see new keyword is used to create an object of the exception. Also, a try-catch block is used to handle the exception.
Since the name string is kept empty, the program threw an exception indicating that the name cannot be empty. This is how the throw keyword works in C#.
Re-throwing an Exception
With the use of the catch block and throw keyword, we can re-throw an exception inside the catch block. We pass it to the caller and let them handle it in a way they want.
Object reference not set to an instance of an object
As you can see, we throw an exception without any parameters because if we throw an exception with a parameter such as ‘throw e‘ then we will not be able to preserve the stack trace of the original exception.
This is how we Re-throw an exception using throw and catch. Also, if you can go through Exception Handling to learn more on how to handle exceptions.
An exception is an event that occurs during the execution of the program i.e. during run–time. This event is unexpected, not known by the program, and disrupts the normal flow of the code. So to handle such errors, we create an exception handler code which will be executed when it finds an exception in a program.
Exception handling is a mechanism to maintain the normal flow of a program by handling runtime errors. The main advantage of exception handling is to ensure that even when an exception occurs, the program’s flow doesn’t break.
C# Exception Classes
The exception classes in C# are mainly directly or indirectly derived from the System.Exception class. Let us go through some of the predefined exception classes derived from the Sytem.SystemException.
Exception
Description
System.DivideByZeroException
It handles the error generated by dividing a number by zero.
System.IndexOutOfRangeException
It handles the error when the array index is out of range.
System.NullReferenceException
It handles the error generated by referencing the null object.
System.ArrayTypeMismatchException
It handles the error of array mismatched type.
System.InvalidCastException
It handles the error generated during typecasting.
System.IO.IOException
It handles the Input-Output errors.
System.OutOfMemoryException
It handles the insufficient free memory error.
System.FieldAccessException
It handles the error generated by invalid private or protected field access.
System.StackOverflowException
It handles the error generated during stack overflow.
C# Exception Handling Keywords
C# provides four different keywords to handle the exception.
try: The try block identifies the block of code for which the exception will be activated. It is followed by a catch block.
catch: The catch indicates the cathching of an exception where you want to catch the error accuring in the program. It is placed right after the try block.
finally: Finally block is used to execute the code followed by the try-catch block. finally block is always executed whether an exception is handled or not.
throw: throw keyword is used to throw an exception when a problem shows up in a program.
C# try/catch and finally block
As discussed above, the try block contains the code that might throw an exception, catch handles an exception if there exists any, and finally block is used for any cleanup work that needs to be done. finally is always executed whether there exists an exception or not.
using System;
namespace ExceptionEg
{
public class Program
{
public static void Main(string[] args)
{
int x = 15;
int y = 0;
int result;
try
{
result = x / y;
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
{
Console.WriteLine("Finally block is executed");
}
}
}
}
Output:
System.DivideByZeroException: Attempted to divide by zero. at.... Finally block is executed
C# User-Defined Exceptions
C# allows us to create our own exception in order to make it more meaningful. User-defined exception classes are derived from the Exception class.
using System;
class TestTemperature
{
static void Main(string[] args)
{
Age age = new Age();
try
{
age.validateAge(18);
}
catch (InvalidAgeException e)
{
Console.WriteLine("InvalidAgeException: {0}", e.Message);
}
}
}
public class InvalidAgeException: Exception
{
public InvalidAgeException(string message): base(message) {}
}
public class Age
{
public void validateAge(int age)
{
if (age < 21)
{
throw (new InvalidAgeException("Age must be greater than 21"));
}
else
{
Console.WriteLine("Age: " + age);
}
}
}
In C#, String is the series of characters or array of characters that represents a text. It is of a reference type (Object) in c#. Various operations are performed on a string such as concatenation, comparison, getting substring, search, trim, replacement, etc.
It is a reference type.
It’s immutable that is its state cannot be changed.
It can contain nulls.
It overloads the operator(==).
Comparing string and String
string and String are the same in C#, the keyword string is an alias of System.String. Both are equivalent and we can use any convention because the string class inherits the properties and methods of the System.String class.
Declaring string using string and System.String class.
using System;
namespace StringProgram
{
class Program
{
static void Main(string[] args)
{
//using array of character
char[] ch = { 's', 'i', 'm', 'p', 'l', 'e' };
string str = new string(ch);
Console.WriteLine(str);
// using "System.String" class
System.String name = "Simple";
Console.WriteLine("Name: " + name);
// using an alias of System.String class
String roll = "43";
Console.WriteLine("Roll: " + roll);
// using string
string score = "80";
Console.WriteLine("Marks: " + score);
}
}
}
Output:
simple Name: Simple Roll: 43 Marks: 80
C# String Properties
Chars
returns a char object at a specified position in the current string object.
Length
returns the length of a specified string
C# String methods
We can perform an operation on strings in order to manipulate them according to the need. An to do that there are few methods present in C#. The following table shows the most commonly used methods in string.
Methods
Description
Compare(String, String)
It is used to compare two strings and returns integer value as an output.
Concat(String, String)
It is used to concatenate the two specified strings.
Contains(String)
It is used to check whether a specified character/string exists or not in the string value.
Copy(String)
It creates a new instance of String with the same value as a specified String.
EndsWith(String)
It is used to check whether the specified character is the last character of the string or not.
Equals(String, String)
It is used to compare two strings. It returns a Boolean value as output.
GetHashCode()
It is used to get the HashValue of the specified string.
IndexOf()
It is used to get the index position of the first occurrence of the specified character.
ToLower()
It is used to transform the specified string into the lower case.
ToUpper()
It is used to transform the specified string into the upper case.
ToString()
It returns the instance of a String.
Insert()
It is used to insert the string/character in the string at the specified position.
Remove()
It is used to delete all the characters from beginning to specified index positions.
Replace()
It is used to replace the character.
Split()
It is used to split the string at the specified value.
StartsWith()
It is used to check whether the specified character is the starting character of the string or not.
Substring()
It is used to find the substring from a specified string.
ToCharArray()
It is used to convert a string into a char array.
Trim()
It is used to remove the extra whitespaces from the beginning and end of the specified string.
Let us go through some of the examples of the above methods mentioned in C#.
Comparing String in C#
using System;
namespace StringProgram
{
class CompString
{
static void Main(string[] args)
{
string str1 = "This is a website";
string str2 = "This is simple2code.com";
if (String.Compare(str1, str2) == 0)
Console.WriteLine("Strings are equal.");
else
Console.WriteLine("Strings are not equal.");
}
}
}
//Output Strings are not equal.
Concatinate Stringin C#
using System;
namespace StringProgram
{
class ConcatString
{
static void Main(string[] args)
{
string str1 = "This is ";
string str2 = "simple2code.com";
Console.WriteLine(String.Concat(str1, str2));
}
}
}
//Output This is simple2code.com
String Contains method in C#
using System;
namespace StringProgram
{
class ContainString
{
static void Main(string[] args)
{
string str1 = "This is simple2code.com";
string str2 = "simple2code.com";
if (str1.Contains(str2))
Console.WriteLine("FOUND!");
//or You can directly search the letters
if (str1.Contains("is"))
Console.WriteLine("FOUND!");
}
}
}
//Output FOUND! FOUND!
Substring method in C#
using System;
namespace StringProgram
{
class SubString
{
static void Main(string[] args)
{
string str1 = "This is simple2code.com";
string subStr = str1.Substring(8);
Console.WriteLine(subStr);
}
}
}
//Output simple2code.com
Special Characters
As we have seen till now the string must be within the quotes. Now there might be cases where the string may need a single quote or double quote to form sentences. Example, John’s book, It’s alright, etc.
Now to use quotes within the string quotes, we need to use backslash escape character. With the help of this, we can turn the special character into a string character.
Escape character
Result
\'
‘
\"
“
\\
\
Let us go through an example to demonstrate the escape character.
using System;
namespace StringProgram
{
class SpecialChar
{
static void Main(string[] args)
{
string str1 = "This is \"simple2code.com\".";
string str2 = "It\'s allright.";
Console.WriteLine(str1);
Console.WriteLine(str2);
}
}
}
//Output: This is "simple2code.com". It's allright.
As you can see in the output, the result is with the quotes where we inserted in the program. This way you can apply special characters in a string.
Inheritance is an important pillar for the foundation of Object-Oriented Programming (OOP). It is a process in C# through which one class can acquire the fields and methods of another class.
Inheritance allows us to inherit or acquire the features of the parent class to the child class so that we can be reuse, extend or modify the attributes and behaviour of another class.
Importance of Inheritance:
For Code Reusability.
For Method Overriding (to achieve runtime polymorphism).
Important terms related to inheritance.
Super Class: The class whose properties and functionalities are inherited by the Subclass is known as superclass(a parent class or a base class).
Sub Class: The class that inherits the property and behavior of the other class(Superclass) is known as subclass( a derived class, extended class, or child class). The subclass can have its own fields and methods along with the fields and methods of the superclass.
Syntax to use inheritance in C#
class derived-className : base-className
{
//fields
//methods
}
Types of Inheritance in C#
Below are the various types of inheritance supported in C#.
1. Single Inheritance
It refers to an inheritance where a child inherits a single-parent class. In the diagram below, class B inherits class A.
Syntax:
class sub_class_name : base_class_name
{
//body of subclass
};
Example: C# example for single inheritance.
using System;
namespace InheritanceEg
{
public class ParentClass
{
public void printParent()
{
Console.WriteLine("This is Parent Class");
}
}
public class ChildClass: ParentClass
{
public void printChild()
{
Console.WriteLine("This is Child Class");
}
}
public class Program
{
public static void Main(string[] args)
{
ChildClass obj = new ChildClass();
obj.printParent();
obj.printChild();
}
}
}
//Output: This is Parent Class This is Child Class
2. Hierarchical Inheritance
The process of deriving more than one class from a base class is called hierarchical inheritance. In other words, we create more than one derived class from a single base class as shown in the diagram below.
Syntax:
class One
{
// Class One members
}
class Two : One
{
// Class Two members.
}
class Three : One
{
// Class Three members
}
Example: C# example for hierarchical Inheritance.
using System;
namespace InheritanceEg
{
public class ParentClass
{
public void printParent()
{
Console.WriteLine("This is Parent Class");
}
}
public class Son: ParentClass //Inheriting ParentClass
{
public void printSon()
{
Console.WriteLine("This is Son's Class");
}
}
public class Daughter: ParentClass //Inheriting ParentClass
{
public void printDaughter()
{
Console.WriteLine("This is Daughter's Class");
}
}
//Main Class
public class Program
{
public static void Main(string[] args)
{
Son s = new Son();
Daughter d = new Daughter();
s.printSon();
s.printParent();
d.printDaughter();
d.printParent();
}
}
}
//Output This is Son's Class This is Parent Class This is Daughter's Class This is Parent Class
3. MultilevelInheritance
In this type inheritance derived class is created from another derived class. In multilevel inheritance, one class inherits from another class which is further inherited by another class. The last derived class possesses all the members of the above base classes.
Example: C# example for multilevel inheritance.
using System;
namespace InheritanceEg
{
public class Animal
{
public void sleep()
{
Console.WriteLine("Animal sleeps");
}
}
public class Dog: Animal //Inheriting Animal
{
public void sound()
{
Console.WriteLine("Dog barks");
}
}
public class Puppy: Dog //Inheriting Dog
{
public void weep()
{
Console.WriteLine("Puppy weeps");
}
}
public class Program
{
public static void Main(string[] args)
{
Puppy p = new Puppy();
p.sleep();
p.sound();
p.weep();
}
}
}
//Output Animal sleeps Dog barks Puppy weeps
4. Multiple Inheritance (through Interface)
Multiple inheritance is the process where the single class inherits the properties from two or more classes.
In the diagram below, class C inherits from both Class A and Class B.
Although, C# does not support multiple inheritance. So we need to use interfaces in C# to use the multiple inheritance. We need to declare the parent class with the interface keyword and the child class with the class keyword.
Example: C# example for multiple inheritance.
using System;
namespace InheritanceEg
{
interface Dog
{
void dogFunc();
}
interface Cat
{
void catFunc();
}
public class Animal: Dog, Cat //Inheriting Dog and Cat interface
{
public void dogFunc()
{
Console.WriteLine("I am a Dog");
}
public void catFunc()
{
Console.WriteLine("I am A Cat");
}
public void animalFunc()
{
Console.WriteLine("All are Animals");
}
}
public class Program
{
public static void Main(string[] args)
{
Animal obj = new Animal();
obj.animalFunc();
obj.dogFunc();
obj.catFunc();
}
}
}
We have learned that the method can be overloaded in C#, in the same way, we can also overload the operator. We can perform the various operations with the same operator in C#.
Operator overloading means performing different operations with the same operator. We can overload most of the built-in operators that are provided by C#. We can also change the user-defined type as well such as structures or classes.
The keyword ‘operator‘ is used to overload an operator. Compile-time polymorphism is achieved through operator overloading.
Syntax:
access_specifier class_name operator operator_symbol (argument_list)
{
// Code to be executed
}
The following table shows which operators present in C# can be overloaded and which are not.
Operators
Description
+, -, !, ~, ++, – –
unary operators take one operand and can be overloaded.
+, -, *, /, %
Binary operators take two operands and can be overloaded.
==, !=, =
Comparison operators can be overloaded.
&&, ||
Conditional logical operators cannot be overloaded directly
+=, -+, *=, /=, %=, =
Assignment operators cannot be overloaded.
Also, =, ., ?:, ->, new, is, sizeof, typeof cannot be overloaded.
Overloading Unary Operators
The return type of unary operator overloading can be of any type except the void. The unary operator includes +, ~, ! and dot (.), these must have any return type but void but the return type must be the type of ‘Type’ for ++ and – operators and must be a bool type for true and false operators.
Also, remember that the true and false operators can be overloaded only as pairs. The compilation error occurs if a class declares one of these operators without declaring the other.
The syntax for overloading unary operator:
public static classname operator operator_symbol (t)
{
// Code to execute
}
Let us go through an example in the C# program for overloading unary operators.
using System;
class Example
{
private int x;
private int y;
public Example() {}
public Example(int i, int j)
{
x = i;
y = j;
}
public void print()
{
Console.WriteLine("X = {0} Y = {1}", x, y);
}
public static Example operator-(Example eg)
{
eg.x = -eg.x;
eg.y = -eg.y;
return eg;
}
}
class MainFunc
{
public static void Main()
{
Example obj1 = new Example(10, 20);
obj1.print();
Example obj2 = new Example();
obj2 = -obj1;
obj2.print();
}
}
Output:
X = 10 Y = 20 X = -10 Y = -20
Overloading Binary Operator
Binary operators are overloaded in pairs such as when an arithmetic operator is overloaded then the corresponding assignment operators also get overloaded automatically. For example, if we overload the + operator then += also gets overloaded automatically.
The syntax for overloading binary operator: we overload binary operator in the same manner as a unary operator, the only difference is the number of parameters here is two.
public static classname operator operator_symbol (t1, t2)
{
// Code to be executed
}
using System;
namespace BinaryOverloading
{
class Example
{
private int num1;
private int num2;
//constructor with no argument
public Example() {}
public Example(int i, int j)
{
num1 = i;
num2 = j;
}
public void print()
{
Console.WriteLine("num1 = {0} num2 = {1}", num1, num2);
}
public static Example operator+(Example eg1, Example eg2)
{
Example temp = new Example();
temp.num1 = eg1.num1 + eg2.num1;
temp.num2 = eg1.num2 + eg2.num2;
return temp;
}
}
class MainBinary
{
public static void Main()
{
Example obj1 = new Example(10, 20);
obj1.print();
Example obj2 = new Example(20, 30);
obj2.print();
Example obj3 = new Example();
obj3 = obj1 + obj2;
obj3.print(); //final result
}
}
}