Class, Fields, property

Class, Fields, property, methods, static modifier

Classes:

Class is one of the data structures in C#. Classes are the user defined data types that represent the state and behavior of an object. State represents the properties and behavior is the action that objects can perform. Classes combines related variables(fields) and functions(methods) together. You create a template of what you want in a object ,and this template is called a class. Example, Car class will have cylinder, auto gear, color etc so that when you initiate a car, you would specify it with 2 cylinders, no auto gear, blue color etc.. Classes are not only feature of C# but is a object oriented concept.In fact it is the base of object oriented programming.

If person is a class, name, height and weight are fields and walk() talk() eat() are methods on that class. Object is instance of a class.

Ex: Jim, Ryan, Stella are objects.

Instance of an class is called as object. For a given class we can have any number of objects. If Telephone is a class, Sony, Ericsson, Panasonic, and Siemens are its objects.

Example of class:

public class Employee

{ private string Name; }

Here employee is a class. Public is called access modifier discussed later. Employee is called identifier. Defining as public makes this class available anywhere in the application/script.

Classes have fields, properties and methods.

Fields:

A field, in C#, is a member of a class or an object of any type that represents a memory location for storing a value.

Fields are used to store data that must be accessible to multiple methods of a class and available throughout the lifetime of an object. Fields enable a class or struct to encapsulate the data with options to specify its accessibility at multiple levels.

In general, a field is used for defining a variable in a class with accessibility as private or protected. A field that needs to be exposed anywhere outside of the class can be encapsulated as a public method, property or indexer.

A field is also known as a class-level variable or member variable.

Declaring Field:

In example below, the class Employee has been modified to include three fields: FirstName, LastName, and Salary.

class Employee { public string FirstName; public string LastName; public string Salary; }

Property:

A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.

Difference between Field and Property:

The fundamental difference is that a field is a position in memory where data of the specified type is stored. A property represents one or two units of code that are executed to retrieve or set a value of the specified type. Member variables or methods in a class or structures are called Fields.

Properties expose fields. Fields should (almost always) be kept private to a class and accessed via get and set properties. Properties provide a level of abstraction allowing you to change the fields while not affecting the external way they are accessed by the things that use your class.

public class MyClass { // this is a field. It is private to your class and stores the actual data. private string _myField; // this is a property. When accessed it uses the underlying field, // but only exposes the contract, which will not be affected by the underlying field public string MyProperty { get { return _myField; } set { _myField = value; } } }

Difference between Field and Variable:

Fields

  • Fields can be marked using Access Modifiers like public, private, protected, internal etc.

  • Field can declare as static. No instance of the class is necessary to access the static field.

  • A field can be declared readonly. A static readonly field is very similar to a constant.

  • A field destroys when the scope of the class is destroyed. In case of Static variable, it only destroyed after all instances of the class/ struct is destroyed.

Variable

  • A variable created in a function destroyed as soon as it loses the scope.

  • Local variable can be given by an implicit type of "var" instead of explicit type.

eg: var i = 10 //implicitly typed

int j = 10 // explicitly typed

  • Below are the restrictions of implicit type variables:

    • "var" can only be used when a local variable is declared and initialized in the same statement.

    • "var cannot be used on fields at class scope.

    • "var" cannot be used as an initialization expression.

  • There are three type of variables in c#. They are "object", "dynamic" and "var". Here var is more type safe. "object" variable provide little information about the type to compiler. "dynamic" variable will not provide any information about the type to compiler.

Important Points:

  • If a value is set to datatype like int k; this is called defining a variable.

  • If same value is defined inside a class it is called field ex: private int k; - check above class employee example. We end the statement with ; . Variables within class are called fields.

  • Field is a pointer to storage, same like variable.

  • Property is working on field, and getting or setting values on fields.

Methods:

A method is a code block that contains a series of statements. A program causes the statements to be executed by calling the method and specifying any required method arguments. In C#, every executed instruction is performed in the context of a method. The Main method is the entry point for every C# application and it is called by the common language runtime (CLR) when the program is started.

A method is a code block containing a series of statements. Methods must be declared within a class or a structure. It is a good programming practice that methods do only one specific task. Methods bring modularity to programs. Proper use of methods bring the following advantages:

  • Reducing duplication of code

  • Decomposing complex problems into simpler pieces

  • Improving clarity of the code

  • Reuse of code

  • Information hiding

Ex:

Public class Calculator
{
private int Add(int a, int b)
{
return a+b;
}
}

Property and Method:

Properties are basically information that an object has. Methods are what an object can do.

Example:

You have an instance (object) from a class named Vehicle, which can represent a car, a truck or a motorbike. Whatever.

  • The vehicle has: Number Plate, Brand, Model, Color. Those are properties.

  • The vehicle can: Turn On, Accelerate, Brake, Horn. Those are methods.

As you can see, Properties are information that you can store and access to. And Methods are the things that you can do, lets say, actions to execute.

Initiating Class:

Since classes are non-primitive ( meaning, user defined data types), we have to allocate memory for the objects (instances of the class) when they are invoked or initiated. We can do this with “new” operator. We don’t have to further bother about how much memory is allocated, how and when to delete/reclaim that memory after process is completed etc. CLR does it for us. We have a process called “garbage collection” in CLR that would automatically removes all objects that are not used. To allocate memory to object use “new” operator and repeat type of class with parentheses and ;

Ex: Employee John = new Employee();

We can also declare this object creation or initiation, using var keyword

Ex: var John = new Employee();

Now we call fields in Employee class as,

john.FirstName = “Firstname”

John.SecondName = “second name”

Here firstname and secondname are fields in class employee.

Static Modifier:

When applied to a class member (field or method), makes that member accessible only via the class, not any objects. Normally when a class is created, we have to create an object and then call it. Ex: Employee John = new Employee();

If we use word “static” in the field, we can directly initiate objects as var John = Employee.Firstname(“Firstname”). You dont have to specify var John = new employee() at all. We do not have to create an object to access static member. We cannot access static members from objects.


Public class Calculator
{
private static int Add(int a, int b)
{
return a+b;
}
}

Public class Employee
{
private static var firstname;
}

Why do we need static modifier:

In normal scenario, we have to initiate each object using Employee() class like this:

Var John = new Employee();

John.firstname = “Firstname”;

Var David = new Employee();

David.firstname = “firstname”;

Every time you create an object, you have to call the class and for every time you call class, memory would be allocated. But with static modifier we use class directly, so that the class will have memory allocation only once. Now we can directly call class and initiate object as,

var John = Employee.firstname(“firstname”);

We use static members in situations where we want only one instance of that member to exist in memory. In the real-world, it’s best to stay away from static as much as you can because that makes writing automated tests for applications hard.

Test class without static modifier:

using System;
 namespace TestApp
 {
     public class person
     {
         public string firstname;
         public string lastname;
         public void writeout()
         {
             Console.WriteLine("I am " + firstname + " " + lastname);
         }
     }
     class Program
     {
         static void Main(string[] args)
         {
             person john = new person();
             john.firstname = "John";
             john.lastname = "smith";
             john.writeout();
         }
     }
 }

Test Class with static modifier:

using System;
 namespace TestApp
 {
     public class person
     {
         public static string firstname;
         public static string lastname;
         public static void writeout()
         {
             Console.WriteLine("I am " + firstname + " " + lastname);
         }
     }
     class Program
     {
         static void Main(string[] args)
         {
             person.firstname = "john";
             person.lastname = "smith";
             person.writeout();

             person.firstname = "mike";
             person.lastname = "jack";
             person.writeout();

         }
     }
 }

Access Modifiers (public, private etc in c# script):

In C# there are 5 different types of Access Modifiers.

Modifier

Description

public

There are no restrictions on accessing public members. Public can be seen by any method in your program/script.

private

Access is limited to within the class definition. This is the default access modifier type if none is formally specified. Private can be seen only by methods in the same class.

protected

Access is limited to within the class definition and any class that inherits from the class

internal

Access is limited exclusively to classes defined within the current project assembly

protected internal

Access is limited to the current assembly and types derived from the containing class. All members in current project and all members in derived class can access the variables.

Last updated