none
Basic get; set; issue RRS feed

  • Question

  • Hi, i'm new to coding and C#, I have a really basic issue that i can't seem to get past. I'm trying to use the get; set; shorthand for adding a property set in an object, but i'm not sure how to set my range. 

    I'm trying to shorten this (for a closely related value):

    private double heightOfSideWall;

                public double HeightOfSideWall
                {
                    get { return heightOfSideWall; }
                    set { if (value > 0)
                            {
                                heightOfSideWall = value;
                            }
                        }
                }

    And my effort looks like this, but the 'get' is underlining, i want to specify the range 0 to infinity:

    public double Width { get; set { if (value > 0) ; } }

    Any advice would be much appreciated :)

    Monday, October 29, 2018 6:47 PM

All replies

  • C# supports defining properties as either "full" properties or as auto properties.

    public class MyObject
    {
       //Auto property - compiler will generate the getter/setter implementations and define the backing field for you
       public int Id { get; set; }
    
       //Full property - you are responsible for the getter and setter methods (if the property needs both), you are also responsible for any backing field they need
       public string Name 
       {
          get { return _name ?? ""; }
          set { _name = value; }
       }
       private string _name;   
    }

    You cannot mix and match them on an accessor level. The auto property syntax is equivalent to this.

    public class MyObject
    {
       public int Id { get; set; }
    
       //The generated code
       /*public int Id 
       {
          get { return _id; }
          set { _id = value; }
       }
       private int _id;*/
    }

    You should use the approach that meets the needs for your specific property. They both generate the same basic code, it's just a productivity enhancement. If you are not simply getting/setting a backing field then an auto property won't work and you'll use the full syntax.

    When using the full syntax you'll often find the property is just a single statement. In these cases you can use an expression body instead of a full statement. Again, just a productivity enhancement, they generate the same code.

    public class MyObject
    {
       //Full property with simple accessors, use expression body
       public string Name
       {
          //Expression body in getter is the expression you want to return (without the return statement)
          get => _name ?? "";
    
          //Expression body in setter is just a single statement
          set => _name = value;
       }
       private string _name;
    }

    In your code the heightOfSideWall is a full property and you could use an expression body for the getter if you wanted. The Width property is trying to mix auto and full and that isn't allowed. Since you want to do something more than get/set a backing field you have to use the full property syntax.

    public class MyObject
    {
       public doublue HeightOfSideWall
       {
          get => heightOfSideWall;
          set 
          {
             if (value > 0) heightOfSideWall = value;
          }
       }
       private double heightOfSideWall;
    
       //You want to do more than get or set the backing field
       //so auto property syntax doesn't work
       public double Width 
       {
          get => width;
          set
          {
             if (value > 0) width = value;            
          }
       }
       private double width;
    }


    Michael Taylor http://www.michaeltaylorp3.net

    Monday, October 29, 2018 7:08 PM
    Moderator
  • https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties

    You can use auto properties. 

    You can have business logic  code that validates data in the object that is not part of the get or set, which is separate from the object's properties

    Monday, October 29, 2018 7:10 PM
  • Thanks a lot for that Michael, I was hoping i was just a bit of syntax away but I understand. In any case the way you've written it is a lot more efficient so that's helpful.

      Thanks again,

      Matthew

    Monday, October 29, 2018 7:35 PM
  • Thanks for your help, I might well try to implement that on my next revision, I'm just trying to get a good handle on the concepts at the moment but I think this looks like a good method 
    Monday, October 29, 2018 7:37 PM
  • Does anyone know the answer to this one as well? I'm trying to instruct the if the numeric value is not valid then i want a written response, but obviously i can't input a string value within a double.

     private double length;

            public double Length     //using get;set; for integer values
            {
                get => length; 
                set { if (value > 0)
                    {
                        double length = value;      //perhaps a bool rather than a double is required
                    }
                    else
                    {
                        string length = "not valid";
                    }
                }                        //need an else string here, not sure how to mix string and numeric outputs
            }

    Monday, October 29, 2018 7:46 PM
  • The correct approach to "invalid" property values is throwing an exception that the caller can handle.

    public double Length
    {
       get => length;
       set 
       {
          if (value <= 0)
             throw new ArgumentOutOfRangeException("Length must be > 0.");
    
          length = value;
       }
    }
    private double length;

    If you really wanted to store string messages instead of throwing an exception you are going to have to write more code.

    public string LengthError
    {
       get => lengthError ?? "";
       private set => lengthError = value;
    }
    
    public double Length
    {
       get => length;
       set 
       {
          if (value > 0)
          {
             length = value;
             LengthError = "";
          } else
          {
             //Reset length to 0??
             LengthError = "Bad value";
          };
       }
    }
    
    private string lengthError;
    
    private double length;
    

    This is non-standard and doesn't really do anything useful though. If nobody looks at your error message then they won't know something went wrong which goes against the purpose of using a property. At this point I'd argue you should be using a method because you have moved beyond the defacto behavior of a property and it would be inconsistent with the rest of .NET.


    Michael Taylor http://www.michaeltaylorp3.net

    Monday, October 29, 2018 7:52 PM
    Moderator
  • Thanks Michael, gosh there's so much to learn. I suspected i was going down the wrong path again with this one, hopefully it will all fall into place in time. I had everything sussed out in excel but the visual outputs just don't compute. I will start afresh until i get all these logics dialled in. I find it so hard to gain an understanding without some feedback on my specific missunderstandings, i really appreciate your help.

     Regards,

     Matthew

    Monday, October 29, 2018 8:07 PM
  • Essentially, I'm trying to have user inputs for a house, through minimal inputs of the length, width, height, pitch of roof, overhang, windows and doors i want the programme to calculate a number of numeric and graphic outputs of material quantities, production and contruction drawings. I think object oriented programming must feature but i'm not sure exactly to what extent. Looking at the methods i can see these can also be usefull, but it seems like i should probably just go into a lot more depth of learning the various functions of the language before i start trying to build my tool. Any more advice would be welcome on what the best areas i should use are. Thanks again for your help in any case.
    Monday, October 29, 2018 10:09 PM
  • https://www.oreilly.com/library/view/expert-c-2008/9781430210191/

    Learn the framework download it and the .NET solution that uses the framework. You then extract the concepts that you learn and apply it to your application. I am not saying use the CSLA framework but understand the BO(s) and apply the concepts to your own program.

    Monday, October 29, 2018 10:47 PM
  • Thanks for that, looks like this is a bigger job than i thought. I've gone ahead and ordered business objects, hopefully it can help me find the best structure in advance before going too far down a road and having to make huge revisions.

     

    Monday, October 29, 2018 11:36 PM
  • Thanks for that, looks like this is a bigger job than i thought. I've gone ahead and ordered business objects, hopefully it can help me find the best structure in advance before going too far down a road and having to make huge revisions.

     

    Take  a hard look at the CSLA BrokenRules that you can apply in the Set in the object's public prosperity, which I just pulled the code out and used it, like rolled my own.

    Also, it shows how to deal with object state, which I have used too, the concept,  as I rolled my own to use with my programs Web and Windows form UI(s).

    http://www.dailycoding.com/Posts/maintaining_dirty_and_new_state_of_objects.aspx

     This may help you too, like using MVP for Windows forms and MVVM for WPF  with WPF being just another Windows desktop program like a Windows form desktop program. 

    https://www.codeproject.com/Articles/228214/Understanding-Basics-of-UI-Design-Pattern-MVC-MVP

    https://en.wikipedia.org/wiki/Separation_of_concerns

    Layered or N-tier.... Look at Layered 

    https://docs.microsoft.com/en-us/previous-versions/msp-n-p/ee658117(v=pandp.10)

    https://docs.microsoft.com/en-us/visualstudio/data-tools/n-tier-data-applications-overview?view=vs-2017

    https://www.codeproject.com/Articles/36847/Three-Layer-Architecture-in-C-NET

    https://www.dofactory.com/net/design-patterns

    All that you are being shown is about design patterns and the interaction of objects in OO.

    Tuesday, October 30, 2018 1:28 AM
  • I really think you're getting ahead of yourself. In all the projects I've ever been on that failed all started out with lofty goals and supposedly awesome technology that would make it happen. In the end the goals weren't met because people were trying to figure out the tech. Your question started with you being new to C# and coding. So I would personally recommend you take a very big step back and not worry about using complex frameworks or fancy libraries that you're going to find online. If you don't already have the basic knowledge then you're still going to struggle with the concepts and at the end of the day you'll end up with nothing.

    I would recommend that you start with the basics. A good book (or website) on C# would be a starter along with some studying on object oriented programming. This will help clarify "how" to write an application. During this time you'll be building out classes and basic functionality that will represent your business objects. If you don't understand when to use classes, properties vs methods and other "fundamental" stuff then you still aren't going to be able to write an application.

    After you have the basic concepts down move on to some more architectural things like design patterns on how to build an application. During this time you can take what you are learning and start building the UI app that has rudimentary functionality that you need. As your skillset evolves you will refactor your application into a more flexible and functional system. There are books on that too. The point is that software development is an iterative process. It is unrealistic to assume that you'll be able to read some books/use some library and suddenly be able to build the app you want. Iterative design is the key to success.

    Given your requirements, start with identifying what data you need from the user to do your calculation. Then build a simple set of classes (using object oriented design) and a UI around that. Next work on the calculations you need. It may not be pretty but when you get done with phase 1 you'll at least have a basic formula calculator working that you can begin using.

    Then you can start phase 2 where you evolve the UI, maybe add some more logic and complexity to do more advanced things. It is at this point that you're going to start realizing you need "X". Then you can start looking for a library that provides "X". You'll know what you need and can better evaluate the library(ies) that may work for you. More importantly you'll already have a baseline to fall back to if things don't work out. This is how complex architectures are built.

    After that you're going to find things that you just "hacked" together or more functionality you need or just things that don't feel right. This is where phase 3 (and beyond) come in. Iterating on your existing, working design to produce more robust, flexible and functional code.


    Michael Taylor http://www.michaeltaylorp3.net

    Tuesday, October 30, 2018 2:16 AM
    Moderator
  • Hi matty1248,

    If the reply is helpful to you, please mark it as answer, it will beneficial to other communities who have the similar issue.

    Best regards,

    Zhanglong


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, October 30, 2018 5:09 AM
    Moderator
  • Thanks a lot for your help, i'm going to go ahead and look at these overall architectural aspects through these links that you sent and the business objects book when it turns up and do that in parallel with learning the basic tools and building up my programming cognition. Really appreciate your input on this and glad that i came to this forum for some feedback as i was getting a bit lost without some feedback
    Thursday, November 1, 2018 11:29 PM
  • Thanks for this Michael, it seems that the course i was doing kind of glossed over classes and I hadn't really appreciated the significance of it, everythings coming along nicely now and i've managed to get past all those problems i was having a few days back. 

    I do have this software project prototype in mind to apply the coding to when i get to a high enough skill set but i'm under no illusions that there isn't a lot of work to do to get to that level. I guess I just want to focus to some extent on working in the areas that will contribute to that, in the first place, and to have something to work on to reinforce the courses that I have been watching and to help dial in the cognition. 

    The software i'm aiming at is in line with the software that my company already makes so i dont feel that there is any issue of technology there, it's more about finding the right architecture and demonstrating effectively what i'm looking to achieve. 

    The pointers you gave me really made me take a step back though and take a fresh understanding, which i'm sure is something that i'll have to do repeatedly before i have a chance at making a working prototype. I am starting to string things together now though and I think i'm starting to get somewhere.

    Thanks a lot for the pointers, I will doubtless have more questions in time or might ask you to make a code review at some point if it's not too much trouble.

    Regards,

    Matthew

    Thursday, November 1, 2018 11:40 PM
  • Hi matty1248,

    Welcome if you have any issues.

    Best regards,

    Zhanglong


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, November 2, 2018 5:54 AM
    Moderator