Introducing classes in C#

Class is the most fundamental of all of the types in C#. A class is a data structure that combines state  (properties) and actions (methods) in a single block. A class provides a definition for dynamically created
instances of the class, also known as objects.

A class will support:
  • Inheritance
  • Polymorphism
  • A mechanism in which derived classes can extend and specialize base classes



Example of the Class Declaration

Code Snippet
  1. using System;
  2. namespace Ch01
  3. {
  4.     class Program
  5.     {
  6.         static void Main(string[] args)
  7.         {
  8.             Person person = new Person()
  9.             {
  10.                 Name = "Person A",
  11.                 Address = "Address of Person A"
  12.             };
  13.             Console.WriteLine(person.ToString());
  14.         }
  15.     }
  16.     public class Person
  17.     {
  18.         public override string ToString()
  19.         {
  20.             return string.Format("Name: {0}\nAddress:{1}", Name, Address);
  21.         }
  22.  
  23.         public string Name { get; set; }
  24.         public string Address { get; set; }
  25.     }
  26.     public class Address { };            /* ; is optional and it used in here
  27.                                          * to show the usage of it.*/
  28. }


This program will produce the output:
Name: Person A
Address: Address of Person A


In above Listing, a class Person is declared with public accessibility using the accessibility modifier as
public. It has two properties—Name, Address (declared using the automatic property declaration)—and this
class overrides the ToString method of the base class (for all the classes in C#) or object class.

Post a Comment