[C#] C# Class Members
Categories: CS
Tags: Class_Member
📋 This is my note-taking from what I learned in the class “Programming 2”
Class Members
Fields and methods inside classes are often referred to as “Class Members.”
Create a Car class with three class members: two fields and one method:
// The class
class MyClass
{
// Class members
string color = "red"; // field
int maxSpeed = 200; // field
public void fullThrottle() // method
{
Console.WriteLine("The car is going as fast as it can!");
}
}
Fields
- Variables inside a class are called fields.
- Access fields by creating an object of the class, and by using the dot syntax (.).
Create an object of the Car class, with the name myObj. Then we print the value of the fields color and maxSpeed:
class Car
{
string color = "red";
int maxSpeed = 200;
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.color);
Console.WriteLine(myObj.maxSpeed);
}
}
You can also leave the fields blank, and modify them when creating the object:
class Car
{
string color;
int maxSpeed;
static void Main(string[] args)
{
Car myObj = new Car();
myObj.color = "red";
myObj.maxSpeed = 200;
Console.WriteLine(myObj.color);
Console.WriteLine(myObj.maxSpeed);
}
}
This(Leave the fields blank) is especially useful when creating multiple objects of one class:
class Car
{
string model;
string color;
int year;
static void Main(string[] args)
{
Car Ford = new Car();
Ford.model = "Mustang";
Ford.color = "red";
Ford.year = 1969;
Car Opel = new Car();
Opel.model = "Astra";
Opel.color = "white";
Opel.year = 2005;
Console.WriteLine(Ford.model);
Console.WriteLine(Opel.model);
}
}
Object Methods
- Methods normally belongs to a class, and they define how an object of a class behaves.
- Access methods with the dot syntax.
- Note that the method must be public. And remember that we use the name of the method followed by two parantheses () and a semicolon ; to call (execute) the method.
class Car
{
string color; // field
int maxSpeed; // field
public void fullThrottle() // method
{
Console.WriteLine("The car is going as fast as it can!");
}
static void Main(string[] args)
{
Car myObj = new Car();
myObj.fullThrottle(); // Call the method
}
}
Why did we declare the method as public, and not static, like in the examples from the C# Methods Chapter?
The reason is simple: a static method can be accessed without creating an object of the class, while public methods can only be accessed by objects.
Use Multiple Classes
We can use multiple classes for better organization (one for fields and methods, and another one for execution).
One for fields and methods:
class Car
{
public string model;
public string color;
public int year;
public void fullThrottle()
{
Console.WriteLine("The car is going as fast as it can!");
}
}
One for execution:
class Program
{
static void Main(string[] args)
{
Car Ford = new Car();
Ford.model = "Mustang";
Ford.color = "red";
Ford.year = 1969;
Car Opel = new Car();
Opel.model = "Astra";
Opel.color = "white";
Opel.year = 2005;
Console.WriteLine(Ford.model);
Console.WriteLine(Opel.model);
}
}
The public keyword is called an access modifier, which specifies that the fields of Car are accessible for other classes as well, such as Program.
Constructors
A constructor is a special method that is used to initialize objects. The advantage of a constructor, is that it is called when an object of a class is created. It can be used to set initial values for fields.
Create a constructor:
// Create a Car class
class Car
{
public string model; // Create a field
// Create a class constructor for the Car class
public Car()
{
model = "Mustang"; // Set the initial value for model
}
static void Main(string[] args)
{
Car Ford = new Car(); // Create an object of the Car class (This will call the constructor)
Console.WriteLine(Ford.model); // Print the value of model
}
}
// Output: "Mustang"
Note that the constructor name must match the class name, and it cannot have a return type (like void or int).
Also note that the constructor is called when the object is created.
All classes have constructors by default: if you do not create a class constructor yourself, C# creates one for you. However, then you are not able to set initial values for fields.
Constructors save time! Take a look at the last example on this page to really understand why.
Constructor Parameters
Constructors can also take parameters, which is used to initialize fields.
The following example adds a string modelName parameter to the constructor. Inside the constructor we set model to modelName (model=modelName). When we call the constructor, we pass a parameter to the constructor (“Mustang”), which will set the value of model to “Mustang”.
class Car
{
public string model;
// Create a class constructor with a parameter
public Car(string modelName)
{
model = modelName;
}
static void Main(string[] args)
{
Car Ford = new Car("Mustang");
Console.WriteLine(Ford.model);
}
}
// Output: "Mustang"
You can have as many parameters as you want:
class Car
{
public string model;
public string color;
public int year;
// Create a class constructor with multiple parameters
public Car(string modelName, string modelColor, int modelYear)
{
model = modelName;
color = modelColor;
year = modelYear;
}
static void Main(string[] args)
{
Car Ford = new Car("Mustang", "Red", 1969);
Console.WriteLine(Ford.color + " " + Ford.year + " " + Ford.model);
}
}
// Outputs Red 1969 Mustang
Tip: Just like other methods, constructors can be overloaded by using different numbers of parameters.
Constructors Save Time
Constructors are very useful, as they help reducing the amount of code.
Without constructor:
class Program
{
static void Main(string[] args)
{
Car Ford = new Car();
Ford.model = "Mustang";
Ford.color = "red";
Ford.year = 1969;
Car Opel = new Car();
Opel.model = "Astra";
Opel.color = "white";
Opel.year = 2005;
Console.WriteLine(Ford.model);
Console.WriteLine(Opel.model);
}
}
With constructor:
class Program
{
static void Main(string[] args)
{
Car Ford = new Car("Mustang", "Red", 1969);
Car Opel = new Car("Astra", "White", 2005);
Console.WriteLine(Ford.model);
Console.WriteLine(Opel.model);
}
}
Static and Non-Static Members
What are Static Members and Non-Static Members in C#?
The member of a class is divided into two categories.
The members (Variables, Constructors, and Methods) which are created by using the static modifier are called static members rest of all are called non-static members.
In other words, we can also define that, the members of a class that does not require an instance either for initialization or execution are known as the static member. On the other hand, the members which require an instance of a class for both initialization and execution are known as non-static members.
Variables
Whenever we declare a variable by using the static modifier or when we declare a variable inside of any static block, then those variables are considered static variables whereas the rest of the others are considered non-static variables.
public class Program
{
int x = 10; // Non-Static Variable
static int y = 20; // Static Variable
public static void Main() // Static Block
{
int a = 10; // By Default Static
}
void SomeMethod() // Non-Static Block
{
int b = 10; // By Default Non-Static
}
}
Static Variables
If a variable is declared static, we can access the variable using the class name.
using System;
namespace StaticKeyword
{
class Student
{
public static string department = "Computer Science"; // Static Variable
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Department: " + Student.department); // Access static variable
Console.ReadLine();
}
}
}
Static Variable VS Instance Variable(= Non-Static Variable)
In C#, every object of a class will have its own copy of instance variables.
class Student
{
public string studentName; // Instance Variable(= Non-Static Variable)
}
class Program
{
static void Main(string[] args)
{
Student s1 = new Student();
Student s2 = new Student();
}
}
- Here, both the objects s1 and s2 will have separate copies of the variable studentName. And, they are different from each other.
- However, if we declare a variable static, all objects of the class share the same static variable. And, we don’t need to create objects of the class to access the static variables.
using System;
namespace StaticKeyword
{
class Student
{
static public string schoolName = "Centennial"; // Static
public string studentName; // Instance(Non-Static)
}
class Program
{
static void Main(string[] args)
{
Student s1 = new Student();
s1.StudentName = "Bill";
// Call the Instance Variable
Console.WriteLine("Name: " + s1.studentName);
// Call the Static Variable
Console.WriteLine("School: " + Student.schoolName);
//======================================================
Student s2 = new Student();
s2.StudentName = "Bill";
// Call the Instance Variable
Console.WriteLine("Name: " + s2.studentName);
// Call the Static Variable
Console.WriteLine("School: " + Student.schoolName);
Console.ReadLine();
}
}
}
Instance? Instance Variable?
- In C#, an instance refers to a specific occurrence or realization of a class. It is an object created from a class blueprint that holds its own set of data and can invoke the class’s methods.
- In C#, an instance variable (also known as an instance field) is a variable that belongs to an instance of a class. It holds unique data for each instance of the class and can have different values for each object created from the class. An instance variable and non-static variable are the same in C#.
Methods
Just like static variables, we can call the static methods using the class name.
class Test
{
public static void display()
{
//Code statement
}
}
class Program
{
static void Main(string[] args)
{
Test.display(); // Method is called using class name
}
}
Static and Non-Static Methods
using System;
namespace StaticKeyword
{
class Test
{
public void display1()
{
Console.WriteLine("Non static method");
}
public static void display2()
{
Console.WriteLine("Static method");
}
}
class Program
{
static void Main(string[] args)
{
Test t1 = new Test();
t1.display1(); // Non-Static
Test.display2(); // Static
Console.ReadLine();
}
}
}
Console.ReadLine()은 사용자의 입력을 기다리고, 사용자가 엔터 키를 누를 때까지 프로그램의 실행을 일시적으로 정지시킵니다. 이렇게 함으로써 프로그램이 종료되지 않고 사용자가 결과를 확인할 수 있도록 합니다.
Main 메서드가 실행되면 프로그램은 코드를 위에서 아래로 순차적으로 실행하고, 마지막 줄인 Console.ReadLine()에 도달하면 프로그램이 멈추고 사용자 입력을 기다리게 됩니다. 사용자가 입력을 하고 엔터 키를 누르면 프로그램이 종료됩니다. 이렇게 함으로써 콘솔 창이 바로 닫히지 않고 결과를 확인할 수 있는 시간을 제공합니다.
Class
In C#, when we declare a class as static, we cannot create objects of the class.
using System;
namespace StaticKeyword
{
static class Test
{
static int a = 5;
static void display()
{
Console.WriteLine("Static Method");
}
static void Main(string[] args)
{
// Create object of Test
Test t1 = new Test();
Console.WriteLine(a);
display();
}
}
}
In the above example, we have a static class Test. We have created an object t1 of the class Test.
Since we cannot make an object of the static class, we get the following error:
- error CS0723: Cannot declare a variable of static type ‘Test’
- error CS0712: Cannot create an instance of the static class
Notice the field and method of the static class are also static because we can only have static members inside the static class.
Inherit a Static Class
In C#, a static class is a class that cannot be instantiated, meaning you cannot create objects or instances of that class. It is used to define types that provide utility functions or hold a collection of related methods and properties that can be accessed directly through the class itself, without creating an instance of the class.
The statement “We cannot inherit a static class in C#” means that you cannot create a derived class that inherits from a static class. In other words, a static class cannot serve as a base class for other classes. Since static classes cannot be instantiated, they are not designed to be extended or inherited.
When you define a class as static using the static keyword, it indicates that the class is meant to be used as a standalone entity with its own set of static members. It is sealed by default, which means it cannot be derived from or serve as a base for other classes. Static classes are primarily used for organizing utility methods or constants and don’t require multiple instances or inheritance.
using System;
public static class MyStaticClass
{
public static void MyStaticMethod()
{
Console.WriteLine("This is a static method.");
}
}
public class MyDerivedClass : MyStaticClass // Error: Cannot inherit from static class 'MyStaticClass'
{
// ...
}
public class Program
{
static void Main(string[] args)
{
MyStaticClass.MyStaticMethod(); // Accessing static method directly from the static class
// MyDerivedClass obj = new MyDerivedClass(); // Trying to create an instance of the derived class - Error
Console.ReadLine();
}
}
Access Static Members within the Class
If we are accessing the static variables and methods inside the same class, we can directly access them without using the class name.
using System;
namespace StaticKeyword
{
class Test
{
static int age = 25;
public static void display()
{
Console.WriteLine("Static method");
}
static void Main(string[] args)
{
Console.WriteLine(age);
display();
Console.ReadLine();
}
}
}
Constructors
If we create the constructor explicitly by the static modifier, then we call it a static constructor and the rest of the others are non-static constructors.
The most important point that you need to remember is the static constructor is the first block of code that gets executed under a class.
No matter how many numbers of objects you created for the class the static constructor is executed only once. On the other hand, a non-static constructor gets executed only when we created the object of the class and that is too for each and every object of the class.
using System;
namespace StaticNonStaticDemo
{
class Example
{
/*
- Static Constructor, Executed only once.
- First block of code to be executed inside a class.
- Before Main Method body start executing, this constructor will execute.
*/
static Example()
{
Console.WriteLine("Static Constructor is Called");
}
/*
- Non-Static Constructor, Executed once per object.
- When we create an instance, this constructor will execute.
*/
public Example()
{
Console.WriteLine("Non-Static Constructor is Called");
}
/*
- Program Execution will start from the Main Method.
- But before executing the Main method body, it will execute the static constructor.
*/
static void Main(string[] args)
{
Console.WriteLine("Main Method Execution Start");
Example obj1 = new Example();
Example obj2 = new Example();
Console.WriteLine("Main Method Execution End");
Console.ReadLine();
}
}
}
// Output:
// Static Constructor is Called
// Main Method Execution Start
// Non-Static Constructor is Called
// Non-Static Constructor is Called
// Main Method Execution End
Private Constructors
Private Constructor is a special instance constructor present in C# language. Basically, private constructors are used in class that contains only static members.
- It is the implementation of a singleton class pattern.
- Use private constructor when class have only static members.
- Using private constructor, prevents the creation of the instances of that class.
- If a class contains only private constructor without parameter, then it prevents the automatic generation of default constructor.
- If a class contains only private constructors and does not contain public constructor, then other classes are not allowed to create instances of that class except nested class.
using System;
namespace PrivateConstDemo
{
public class Geeks
{
// Private constructor without parameter
private Geeks
{
Console.WriteLine("Private Constructor");
}
}
// Driver Class
class GFG
{
// Main Method
static void Main()
{
// This line raise error because the constructor is inaccessible!
Geeks obj = new Geeks();
}
}
}
using System;
namespace PrivateConstDemo
{
class Geeks
{
// Variables
public static string name;
public static int num;
// Create private constructor using private keyword
private Geeks()
{
Console.WriteLine("Welcome to Private Constructor");
}
// Default constructor with parameters
public Geeks(string a, int b)
{
name = a;
num = b;
}
}
class GFG
{
// Main Method
static void Main()
{
// This line raises error because the constructor is inaccessible!
Geeks obj1 = new Geeks();
// Here, the only default constructor will invoke
Geeks obj2 = new Geeks("Ankita", 2);
/* Here, the data members of Geeks
- Class are directly accessed because they are static members.
- Static members are accessed directly with the class name
*/
Console.WriteLine(Geeks.name + ", " + Geeks.num);
}
}
}
Leave a comment