top of page
Writer's picturehr9083

Objects in C#


 C# 

C# is a general-purpose, modern programming language developed by Microsoft as part of its .NET initiative. It is widely used for building a variety of applications including desktop, web, mobile, cloud, and game development. C# combines the power and flexibility of C++ with the simplicity of Visual Basic, making it a versatile language suitable for a wide range of programming tasks. 

  • It supports object-oriented programming (OOP) principles like encapsulation, inheritance, polymorphism, and abstraction. 

  • C# is statically typed, ensuring type safety and catching errors at compile-time. 

  • It features automatic memory management through a garbage collector, simplifying memory management. 

  • With .NET Core (now .NET 5 and .NET 6), C# is cross-platform, running on Windows, macOS, and Linux. 

  • C# offers a rich standard library and ecosystem, including extensive built-in classes and APIs. 

  • It supports asynchronous programming with async and await for non-blocking code. 

  • C# development is often done using Visual Studio, Microsoft's powerful integrated development environment (IDE). 

 

Why we need C# 

C# is a versatile and powerful programming language that serves various purposes, making it indispensable for numerous applications: 

Versatility: C# can be used for a wide range of software development tasks, including desktop applications, web applications, mobile apps, games, cloud-based services, and enterprise software. 

Integration with .NET Framework and .NET Core: C# is closely integrated with the .NET Framework and .NET Core, which provides extensive libraries and frameworks for building robust, scalable, and secure applications. 

Object-Oriented Programming (OOP): C# supports OOP principles such as encapsulation, inheritance, and polymorphism, making it easier to manage and maintain complex software systems. 

Type Safety: C# is a statically typed language, which means that type checking is performed at compile time, reducing the likelihood of runtime errors and improving code reliability. 

Memory Management: C# features automatic memory management through garbage collection, freeing developers from manual memory management tasks and reducing the risk of memory leaks and other memory-related issues. 

Cross-platform Development: With the advent of .NET Core, C# has become a cross-platform language, enabling developers to write code that runs on multiple platforms such as Windows, macOS, and Linux. 

Rich Ecosystem: C# benefits from a vibrant ecosystem with a large community of developers, extensive documentation, third-party libraries, and tools, which accelerate development and troubleshooting processes. 

Performance: C# offers high performance, especially when used in conjunction with the .NET runtime, JIT (Just-In-Time) compilation, and optimization techniques. 

Language Features: C# continues to evolve with new language features and improvements, enhancing developer productivity and enabling the implementation of modern programming paradigms. 

Support for Modern Development Practices: C# supports modern development practices such as asynchronous programming, LINQ (Language Integrated Query), and functional programming techniques, facilitating the development of efficient and expressive code. 

Overall, C# provides developers with a powerful and flexible tool for building a wide range of software solutions, from simple scripts to complex enterprise applications. 

 

How to write code in C# 

Here's a simple "Hello, World!" example:   




using System: This line imports the System namespace, which contains fundamental classes and base types that are essential for basic C# programming. 

class Program: This declares a class named Program. In C#, the entry point of a console application is typically defined within a class named Program

static void Main(): This is the entry point of the program, where execution begins. It's a method called Main, which is declared as static, returns void and takes no parameters. 

Console.WriteLine("Hello, World!"): This statement writes the text "Hello, World!" followed by a newline to the console output. Console is a class in the System namespace that provides methods for interacting with the console, and WriteLine is one of its methods used to write a line of text to the console. 

                                  Oops 

Object-oriented programming (OOP) is a programming paradigm that revolves around the concept of objects, which are instances of classes that encapsulate data and behaviour. C# fully supports OOP principles, including:  

  • Classes and Objects 

  • Inheritance 

  • Abstraction 

  • Polymorphism 

  • Encapsulation  

 

 

Classes and Objects: In C#, you define classes to represent entities in your program. Objects are instances of these classes that contain data (fields or properties) and behaviour (methods). For example: 

 

 



Breakdown of the above code: 

  • class Car: Declares a class named Car

  • {: Marks the beginning of the class definition block. 

  • public string Model: Declares a public field Model of type string

  • public int Year: Declares a public field Year of type int

  • public Car(string model, int year): Defines a constructor with parameters model and year

  • {: Marks the beginning of the constructor block. 

  • Model = model: Assigns the model parameter to the Model field. 

  • Year = year: Assigns the year parameter to the Year field. 

  • }: Marks the end of the constructor block. 

  • public void Start(): Defines a method named Start with no return value. 

  • {: Marks the beginning of the method block. 

  • Console.WriteLine("The car is starting...");: Writes a message indicating the car is starting. 

  • }: Marks the end of the method block. 

  • }: Marks the end of the class definition block. 

  • Car myCar = new Car("Toyota", 2022): Creates a new Car object named myCar with model "Toyota" and year 2022. 

 

Inheritance: Inheritance allows a class (subclass or derived class) to inherit fields and methods from another class (superclass or base class). C# supports single inheritance, where a class can inherit from only one base class. 

 For example: 

 




Breakdown of the above code:  

 

Animal Class:  

  • Defines a method Eat() to represent eating behaviour. 

  • When Eat() is called, it prints "The animal is eating..." to the console. 

Dog Class:  

  • Inherits from the Animal class, implying that a Dog is a type of Animal. 

  • Adds its own method Bark() to represent barking behavior. 

  • When Bark() is called, it prints "Woof! Woof!" to the console. 

Program Class: 

  • Contains the Main() method, which is the entry point of the program. 

  • Inside Main(), it creates an instance of Dog named myDog. 

  • Invokes myDog.Eat(), which calls the Eat() method inherited from Animal, resulting in "The animal is eating..." being printed. 

  • Invokes myDog.Bark(), which calls the Bark() method defined in Dog, resulting in "Woof! Woof!" being printed. 

 

Abstraction: Abstraction involves hiding the implementation details of a class and exposing only the relevant features to the outside world. Abstract classes and interfaces are used to achieve abstraction in C#. 

 For example: 

 




Breakdown of the above code: 

  • using System: This line includes the System namespace, which contains fundamental types and base classes. 

  • abstract class Person: Declares an abstract class named Person, serving as a blueprint for other classes representing people. 

  • protected string name and protected int age: Declare two protected fields, name and age, which are accessible within the class and its derived classes. 

  • public abstract string Name { get; set; } and public abstract int Age { get; set; }: Declare abstract properties Name and Age, which must be implemented by any derived class. These properties provide access to the name and age fields, respectively. 

  • public abstract void DisplayInfo()  Declares an abstract method DisplayInfo(), which must be implemented by any derived class. This method is responsible for displaying information about a person. 

  • class ConcretePerson : Person: Defines a concrete class ConcretePerson that inherits from the abstract class Person

  • public override string Name {...} and public override int Age {...}: Override the abstract properties Name and Age in the ConcretePerson class, providing concrete implementations for them. 

  • public override void DisplayInfo() {...}: Overrides the abstract method DisplayInfo() in the ConcretePerson class, providing a concrete implementation that displays the name and age of a person using Console.WriteLine(). 

  • Class Program: Declares a class named Program, which contains the Main method, the entry point of the program. 

  • static void Main(string[] args) {...}: Defines the Main method, which serves as the entry point for the program. It creates an instance of ConcretePerson, sets its Name and Age properties, and then calls the DisplayInfo() method to display information about the person. 

 

 

 

 

 

 

 

 

 

 

 

Polymorphism: Polymorphism allows objects of different classes to be treated as objects of a common superclass. There are two main types of polymorphism in C#: compile-time polymorphism (also known as method overloading and operator overloading) and runtime polymorphism (achieved through method overriding and interface implementation).  

For example: 

 

 



 

Breakdown of the above code: 

  • The code defines an abstract class Person, which serves as a base class for specific types of people. 

  • Person class has an abstract method DisplayInfo(), which means any class inheriting from Person must implement this method. 

  • There are two concrete classes that inherit from Person: Employee and Student

  • Both Employee and Student classes override the DisplayInfo() method with their own implementations. 

  • The Employee class implementation of DisplayInfo() prints "Employee Info" to the console. 

  • The Student class implementation of DisplayInfo() prints "Student Info" to the console. 

  • In the Main() method, two variables of type Person are declared and initialized with instances of Employee and Student respectively. 

  • Polymorphism is demonstrated as the DisplayI


  • nfo() method is called on both employee and student objects, but the actual method called depends on the type of the object. 

  • When employee.DisplayInfo() is called, "Employee Info" is printed to the console. 

  • When student.DisplayInfo() is called, "Student Info" is printed to the console. 

Top of Form 

 

Encapsulation: Encapsulation is the bundling of data and methods that operate on the data within a single unit (class). In C#, you can use access modifiers like public, private, protected, and internal to control the visibility of members within a class.  

For example:  

 

 



 

Breakdown of the above code: 

  • using System: This line includes the System namespace, which contains fundamental types and base classes. 

  • class Person: This class represents a person and encapsulates their name and age. 

  • private string name; and private int age: These lines declare private fields name and age to store the name and age of a person, respectively. These fields are not directly accessible from outside the Person class. 

  • public string Name { get { return name; } set { name = value; } }: This is a property Name, which provides controlled access to the name field. It has a getter and a setter, allowing getting and setting the value of name while enforcing encapsulation. 

  • public int Age { get { return age; } set { age = value; } }: Similarly, this is a property Age providing controlled access to the age field. 

  • class Program: This class serves as the entry point of the program. 

  • static void Main(string[] args): This is the Main method, which is the entry point of the program. It creates an instance of the Person class, sets its Name and Age properties, and then outputs the values of these properties to the console. 

  • Person person = new Person(): This line creates a new instance of the Person class named person

  • person.Name = "John"; and person.Age = 30: These lines set the Name property to "John" and the Age property to 30 for the person object. 

  • Console.WriteLine("Person's Name: " + person.Name): This line prints the name of the person to the console. 

  • Console.WriteLine("Person's Age: " + person.Age): This line prints the age of the person to the console. 

 

 

6 views0 comments

Recent Posts

See All

Comments


bottom of page