Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Globalization;
- namespace CSharpTest
- {
- class PropertiesTesting
- {
- private int somePrivateVar;
- public string SomePrivateThing { get; } // read only property
- public int SomePrivateVar { get; } //
- public PropertiesTesting(string var) => SomePrivateThing = var; // ctor can change it
- public PropertiesTesting(int var) => SomePrivateVar = var; // ctor can change this one too
- //public void ChangeSomEPrivateThing() => SomePrivateThing = "gg"; // but method can't
- //public void ChangeSomePrivateVar() => SomePrivateVar = 1; // also can't
- public void ChangeSomePrivateVar() => somePrivateVar = 1; // but we can do this!
- /*
- but there is the problem: in this case we should manually specify that value will be linked with property
- or there will be two different entities, so in this case
- "somePrivateVar"(field) and "SomePrivateVar"(property) aren't same object
- we will show how it should be done for var value and Var property in Entity class
- */
- public void showData()
- {
- Console.WriteLine($"SomePrivateThing = {SomePrivateThing}");
- Console.WriteLine($"SomePrivateVar = {SomePrivateVar}");
- Console.WriteLine($"somePrivateVar = {somePrivateVar}");
- }
- }
- class Entity
- {
- private int var; // field
- public int Var => var; // read only property
- //public Entity(int value) => Var = value; here ctor already can't initialize read only property
- public Entity(int value) => var = value; // but it can initialize field
- // same to methods
- //public void Method() => Var = 100; there is no way!
- public void Method() => var = 100; // here it is!
- public void showData() => Console.WriteLine($"var = {var}\nVar = {Var}");
- }
- class Program
- {
- static void Main(string[] args)
- {
- CultureInfo.CurrentCulture = new CultureInfo("en-US", false);
- PropertiesTesting pt = new PropertiesTesting("auf");
- // pt.SomePrivateThing = "awooooo!"; can't do such stuff - compile error
- PropertiesTesting pt2 = new PropertiesTesting(100);
- pt2.ChangeSomePrivateVar();
- pt2.showData(); // "", 100 and 1
- Entity e = new Entity(5);
- e.showData(); // 5 and 5
- e.Method();
- e.showData(); // 100 and 100 as it should be
- Console.ReadKey();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement