-1

I want ask you, how should i set and get properties values? Should i do this, for example directly from another class and set property as public property or maby better practise is to set property as private and change it or get it by using public function implemented in this class?

first case:

//Class.cs
public class Class
    {
        public int Number{ get; set; }
    }
//AnotherClass.cs
public class AnotherClass
    {
        Class class = new Class();
        class.Number = 2;
        int number = class.Number;
    }

Second case:

//Class.cs
public class Class
    {
        private int Number{ get; set; }

        public void setNumber(int number)
        {
           Number =  number;
        }
        public int getNumber()
        {
           return Number;
        }
    }
//AnotherClass.cs
public class AnotherClass
    {
        Class class = new Class();
        class.setNumber(2);
        int number = class.getNumber();
    }

this code is obviously a bit simplified ...

Pekler
  • 17
  • 4
  • 1
    As with many things, *it depends*. – RoadieRich Mar 03 '22 at 21:04
  • But for the same purpose, is any option better or maby safer? Is it ok, to do it like in 1st case? – Pekler Mar 03 '22 at 21:10
  • Definitely first case. This is what properties are made for. – Clemens Mar 03 '22 at 21:39
  • You should look into these related questions. https://stackoverflow.com/questions/17881091/getter-and-setter-declaration-in-net https://stackoverflow.com/questions/1568091/why-use-getters-and-setters-accessors – NTINNEV Mar 03 '22 at 22:46
  • Thank you for answer, now i get it, I should implement the behavior in extended setter / getter instead of creating new mothod. – Pekler Mar 04 '22 at 15:48

1 Answers1

1

I would do that:

//Class.cs
public class Class
{
    public int Number { get; set; }
}

//AnotherClass.cs
public class AnotherClass
{
    Class class = new Class
    {
        Number = 2    // use , (comma) to separate if needed when
                      // the class has other fields
    };
    int number = class.Number;
}
Fredy
  • 532
  • 3
  • 11
  • Ok, ty for answer, but why it's good option? – Pekler Mar 04 '22 at 15:47
  • 1
    I saw your comment in your question up there, so yes, customize the setter / getter as you wish. There are many reasons to use the accolades { } like I showed in the AnotherClass: first, it's about having the Visual Studio autocomplete feature which lets you write the code very quickly. To see that, you need to have more that 1 field of course, in your class. Once you used the field, the autocomplete won't propose it a second time, it's very convenient. When you are working with embedded classes like in XML or JSON stuff, you also should, for more clarity use this, than your 2nd class case. – Fredy Mar 04 '22 at 17:17
  • Ok, i get it, thak you. – Pekler Mar 08 '22 at 17:37