C# Encapsulation

Çağlar Can SARIKAYA
.Net Programming
Published in
2 min readMar 11, 2022
sorry for the low-quality gif :)

Hi everyone, there is two way to create a property by snippets, one is type prop then pres tab + tab other one is to write propfull then press tab + tab, you will achieve your property.

What is Property?

So we should understand first what is the field? let's assume you have a class named by person, this person's class name feature is to keep person names. Name is a feature for person class. So you should define this;

public string Name;

It's a field definition, but you can not access this. This creates a place in your ram but you do not allow to read/write this place. Even this access modifier is set public.

So you need a property to access this field.

public string Name{get; set;}

It is property definition, after c# 3.0 you can easily create like that and it knows there is the field behind this. But this is works like what is the field you will allow to read&write directly. If you want to modify data, encapsulation is started here.

Basically, you will create a capsule and put your property into it. Get is for reading the field, the set is for writing data to the field. When you use propfull snippet, you will see the default creation of one field and one property, you need the defined field because you want to modify it. Fields should define as private. Because the name is a feature of a person, you shouldn't access this directly

private string name;
public string Name
{
get
{
return "Mr." + name;
}
set { name = value; }
}

Note: When creating encapsulation we use PascalCase on property names, camelCase on field names or some of us uses underscore on field

Resources

https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/names-of-type-members

--

--