Home  • Courses • Software Engineering

Classes and Objects C#

Object Oriented programming organizes code by creating types in the form of classes. These classes contain the code that represents a specific entity. A class definition is like a blueprint that specifies what the type can do. The following list includes all the various kinds of members that may be declared in a class, struct, or record. 1. Constructors 2. Constants 3. Fields 4. Finalizers 5. Methods 6. Properties 7. Indexers 8. Operators 9. Events 10. Delegates 11. Classes 12. Interfaces 13. Structure types 14. Enumeration types
class TestClass
{
    // Methods, properties, fields, events, delegates
    // and nested classes go here.
}
An object is basically a block of memory that has been allocated and configured according to the blueprint. A program may create many objects of the same class. Objects are also called instances, and they can be stored in either a named variable or in an array or collection. Client code is the code that uses these variables to call the methods and access the public properties of the object.
using System;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
    // Other properties, methods, events...
}

class Program
{
    static void Main()
    {
        Person person1 = new Person("Leopold", 6);
        Console.WriteLine("person1 Name = {0} Age = {1}", person1.Name, person1.Age);

        // Declare new person, assign person1 to it.
        Person person2 = person1;

        // Change the name of person2, and person1 also changes.
        person2.Name = "Molly";
        person2.Age = 16;

        Console.WriteLine("person2 Name = {0} Age = {1}", person2.Name, person2.Age);
        Console.WriteLine("person1 Name = {0} Age = {1}", person1.Name, person1.Age);
    }
}
/*
    Output:
    person1 Name = Leopold Age = 6
    person2 Name = Molly Age = 16
    person1 Name = Molly Age = 16
*/

Comments 0


Copyright © 2024. Powered by Intellect Software Ltd