0

I have a class with several string fields. This class represents a model for a serialization, so I have to check the length of its fields.

I do so with

public String Address {
        get { return this.address; }
        set {
              if (value.Length > 15)
              {
                this.address= value.Substring(0,15);
              }
               else { this.address = value; }
            }
    }

All previous properties are being successfully set, but at certain point I get an error of 'null reference exception'.

I would avoid a solution like

public String Address {
        get { return this.address; }
        set {
             if(value!=null){ 
             if (value.Length > 15)
              {
                this.address= value.Substring(0,15);
              }
               else { this.address = value; }
            }
          }
    }

What do you suggest?

dymanoid
  • 14,771
  • 4
  • 36
  • 64
jon
  • 13
  • 1
  • 8
  • 2
    In order to *prevent* an NRE you surely have to *check* for null. What´s your problem on doing so? – MakePeaceGreatAgain Sep 19 '17 at 07:46
  • I do not understand why? why works for previous field (city,region...) and not for next ??? – jon Sep 19 '17 at 07:49
  • 3
    @jon Probably because `value` is never null for city, region...? – MatSnow Sep 19 '17 at 07:53
  • Ok i trie to chek on get – jon Sep 19 '17 at 07:53
  • Are you sure you've got NRE during setting value of Address property? Maybe you've got problem during getting value. You should also check for null in Address property get method – Adrian Bystrek Sep 19 '17 at 07:54
  • @MatSnow is probably right; if you call `value.Length` and value is null, you can't reach `Length`, hence the `NullReferenceException`. If you don't access `Length` in your other properties or if their are never null, you never get this error. – benichka Sep 19 '17 at 07:55
  • @Lazys What do you want to check within the getter? It may *never* throw an NRE, as `this`can´t be `null`. – MakePeaceGreatAgain Sep 19 '17 at 07:57
  • I have to create a CSV from this class model so i test the lenght of property and i do in set ! I have to respect the lenght for every column – jon Sep 19 '17 at 07:58
  • I confirm that i get error if check the null on get ! if i check the null on set i solve ... but i dont understand – jon Sep 19 '17 at 08:01
  • MatSnow i think you right! – jon Sep 19 '17 at 08:03

0 Answers0