Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Property

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 12

https://dotnettutorials.

net/lesson/properties-csharp/

Why do we need Properties in C#?

In order to encapsulate and protect the data members (i.e. fields or variables) of a class, we use
properties in C#. The Properties in C# are used as a mechanism to set and get the values of
data members of a class outside of that class. If a class contains any values in it and if we want
to access those values outside of that class, then we can provide access to those values in 2
different ways. They are as follows:

1. By storing the value under a public variable, we can give direct access to the value
outside of the class.
2. By storing that value in a private variable, we can also give access to that value outside of
the class by defining a property for that variable.

What is a Property in C#?

A Property in C# is a member of a class that is used to set and get the data from a data field (i.e.
variable) of a class. The most important point that you need to remember is that a property in C#
is never used to store any data, it just acts as an interface or medium to transfer the data. We
use the Properties as they are public data members of a class, but they are actually special
methods called accessors.

What are Accessors in C#?

The Assessors are nothing but special methods which are used to set and get the values from
the underlying data member (i.e. variable) of a class. Assessors are of two types. They are as
follows:

1. Set Accessor
2. Get Accessor

What is a Set Accessor?

The set accessor is used to set the data (i.e. value) into a data field i.e. a variable of a class. This
set accessor contains a fixed variable named value. Whenever we call the property to set the
data, whatever data (value) we are supplying will come and store inside the variable called value
by default. Using a set accessor, we cannot get the data.

Syntax: set { Data_Field_Name = value; }

What is Get Accessor?

The get accessor is used to get the data from the data field i.e. variable of a class. Using the get
accessor, we can only get the data, we cannot set the data.

Now, you may have one question. Why not make the variables public? Why are we are creating the
variables as private and why we are creating public properties for them? The answer is to achieve the
Encapsulation Principle.

1
The C#.NET supports four types of properties. They are as follows

1. Read-Only Property
2. Write Only Property
3. Read Write Property
4. Auto-Implemented Property

Let us understand each of the above properties in detail with examples.

What is Read-only Property in C#?

The Read-Only Property is used to read the data from the data field i.e. read the data of a
variable. Using this Read-Only Property, we cannot set the data into the data field. This property
will contain only one accessor i.e. get accessor.
Syntax:
AccessModifier Datatype PropertyName
{
      get {return DataFieldName;}
}

What is Write only Property in C#?

The Write-Only Property is used to write the data into the data field i.e. write the data to a
variable of a class. Using this Write-Only Property, we cannot read the data from the data field.
This property will contain only one accessor i.e. set accessor.
Syntax:
AccessModifier Datatype PropertyName
{
       set {DataFieldName = value;}
}

What is Read Write Property in C#?

The Read-Write Property is used for both reading the data from the data field as well as writing
the data into the data field of a class. This property will contain two accessors i.e. set and get.
The set accessor is used to set or write the value to a data field and the get accessor is read the
data from a variable.
Syntax:
AccessModifier Datatype PropertyName
{
      set {DataFieldName = value;}
      get {return DataFieldName;}
}

Note: Whenever we create a property for a variable, the data type of the property must be the same as
the data type of the variable. A property can never accept any argument.

What are the advantages of using Properties in C#?

1. Properties will provide the abstraction to the data fields.


2. They also provide security to the data fields.
3. Properties can also validate the data before storing it in the data fields.
2
What are Auto-Implemented Properties in C#?

If you do not have any additional logic while setting and getting the data from a data field i.e. from
a variable of a class, then you can make use of the auto-implemented properties which was
introduced as part of C# 3.0. The Auto-Implemented Property in C# reduces the amount of code
that we have to write. When we use auto-implemented properties, then the C# compiler implicitly
creates a private, anonymous field or variable for that property behind the scene which is going
to hold the data.
Syntax: Access_specifier Datatype Property_Name { get; set; }
Example: public int A { get; set; }

using System;
public class Employee
{
public int Id { get; set; }
public int Age { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
class Program
{
static void Main(string[] args)
{
Employee employee = new Employee();
employee.Id = 101;
employee.Age = 101;
employee.Name = "Pranaya";
employee.Address = "BBSR, Odisha, India";
Console.WriteLine("Employee Details:");
Console.WriteLine($"Id: {employee.Id}");
Console.WriteLine($"Name: {employee.Name}");
Console.WriteLine($"Age: {employee.Age}");
Console.WriteLine($"Address: {employee.Address}");
}
}

3
PRIMER:

using System; class Program


public class Student {
{ static void Main(string[] args)
private int _ID; {
private string _Name; Student student = new Student();
private int _PassMark = 35; student.ID = 101;
public int ID student.Name = "Pranaya";
{
set Console.WriteLine($"ID = {student.ID}");
{ Console.WriteLine($"Name = {student.Name}");
if (value < 0) Console.WriteLine($"Pass Mark =
{ {student.PassMark}");
throw new Exception
("ID value should be greater than zero"); }
} }
_ID = value;
}
get
{
return _ID;
}
}
public string Name
{
set
{
if (string.IsNullOrEmpty(value))
{
throw new Exception("Name should not be empty");
}
_Name = value;
}
get
{
return string.IsNullOrEmpty(_Name) ? "No Name" : _Name;
}
}
public int PassMark
{
get
{
return _PassMark;
}
}
}

4
What does it mean by Recursive Function in C#?

Function calling itself is called Recursion. Or in simple words we can say that recursion is a
process in which a function calls itself repeatedly until some specified condition has been
satisfied. It is similar to a loop, in the loop, as long as the loop condition is satisfied, the loop
executes and in the same manner, as long as the condition is satisfied, the function will call itself.

In order to solve a problem recursively, two conditions must be satisfied. First, the problem must
be written in a recursive form so that the function will call itself, and second, the problem
statement must include a stopping condition so that we can stop the function call.

The most important point that you need to remember is that if a recursive function contains any
local variables, a different set of local variables will be created during each call. The variables will
represent a different set of values each time the function is executed. Each set of values will be
stored on the stack memory. If this is not clear at the moment, then don’t worry, we explain these
hings when we start discussing the
examples

5
using System;
namespace RecursionDemo using System;
{ namespace RecursionDemo
public class Program { {
public static void Main() { public class Program {
int x = 3; public static void Main() {
fun1(x); int x = 3;
} fun1(x);
public static void fun1(int n) { }
if (n > 0) public static void fun1(int n) {
{ if (n > 0)
Console.Write("{0} ",n); {
fun1(n - 1); fun1(n - 1);
} Console.Write("{0} ",n);
}
} }
} // output 3,2,1 } output 1,2,3
}

6
7
using System;
namespace RecursionDemo
{
public class Program
{
static void Main(string[] args)
{
int x = 5;
Console.WriteLine("The factorial of {0} is {1}",x, factorial(x));
}

public static int factorial(int number)


{
if (number == 1)
{
return (1); /* exiting condition */
}
else
{
return (number * factorial(number - 1));
}
}
}
}
Output: The factorial of 5 is 120

8
What are the advantages of Recursion in C# Language?

1. Function calling-related information will be maintained by recursion.


2. Stack evaluation will take place by using recursion.
3. Prefix, postfix, and infix notation will be evaluated by using recursion

What are the disadvantages of Recursion in C# Language?

1. It is a very slow process due to stack overlapping.


2. The recursive program can create stack overflow.
3. The recursive program can create infinite loops.

9
What
is a Constructor in C#?

It is a special method present inside a class responsible for initializing the variables of that class.
We will come to this point later part of this article.

The name of the constructor method is exactly the same name as the class in which it was
present. You cannot change the name. If your class name is Employee, then the name of the
constructor method is going to be Employee, and if your class name is Student, then the
constrictor name is also going to be Student.

The constructor method does not return any value. That means it is a non-value returning
method. Generally, methods are of two types i.e. value returning and non-value returning and
constructors are purely non-value returning. That is, they never return any value.

Each and every class requires this constructor if we want to create the instance of the class. If we don’t
have a constructor, then we cannot create an instance of the class.

we call this an Implicit Constructor., kompajler to radi sam by default.


And if we defined the same thing, then it is called an explicit constructor.

here are five types of constructors available in C#, they are as follows

10
1. Default or Parameter Less Constructor
2. Parameterized Constructor
3. Copy Constructor
4. Static Constructor
5. Private Constructor

Default or Parameterless Constructors in C#

If a constructor method does not take any parameters, then we call that a Default or Parameter
Less Constructor. These constructors can be defined by a programmer explicitly or else will be
defined implicitly provided there is no explicit constructor under the class.

Default or Parameterless Constructors are again classified into two types. They are as follows:

1. System-Defined Default Constructor


2. User-Defined Default Constructor

As a programmer, if we are not defined any constructor explicitly in our program, then by default the
compiler will provide one constructor at the time of compilation.

What is a User-Defined Default Constructor in C#?

The constructor which is defined by the user without any parameter is called the user-defined
default constructor. This constructor does not accept any argument but as part of the constructor
body, you can write your own logic.

using System;
namespace ConstructorDemo
{
class Employee
{
public int Id, Age;
public string Address, Name;
public bool IsPermanent;

//User Defined Default Constructor


public Employee()
{
Id = 100;
Age = 30;
Address = "Bhubaneswar";
Name = "Anurag";
IsPermanent = true;
}

public void Display()


{
Console.WriteLine("Employee Id is: " + Id);
Console.WriteLine("Employee Age is: " + Age);
Console.WriteLine("Employee Address is: " + Address);
Console.WriteLine("Employee Name is: " + Name);
Console.WriteLine("Is Employee Permanent: " + IsPermanent);
}
}

class Program
{
11
static void Main(string[] args)
{
Employee e1 = new Employee();
e1.Display();

Console.ReadKey();
}
}
}

12

You might also like