-5

I constructed the following class:

   public class FSCServerLocator
    {
        public string userLocation { get; private set; }

        public string FSCServer
        {
            get
            {
                switch (userLocation)
                {
                    default:
                        return @"\\himgwsfs01\QT_Tools\Diagnose\09_SWT_FSCs";
                }
            }
        }

        public FSCServerLocator(string location)
        {
            if (string.IsNullOrWhiteSpace(userLocation))
            {
                throw new Exception("No location included at initialization");
            }
            //parameter filtering
            userLocation = location;
        }
    }
}

And calling the object like this

var fscServerLocator = new FSCServerLocator(@"\\himgwsfs01\QT_Tools\Diagnose\09_SWT_FSCs");

When running the program an unhandled exception is thrown saying {"No location included at initialization"}. I only want to see if the location is reached but maybe I am missing something since i am new in c#

Răzvan Bălan
  • 33
  • 1
  • 13
  • 1
    In the line `if (string.IsNullOrWhiteSpace(userLocation))` you're using `userLocation` instead of the argument `location`. – dcg Mar 13 '17 at 17:24

2 Answers2

5

You need to change your constructor to look at location instead of userLocation (see below) in order to avoid this exception:

    public FSCServerLocator(string location)
    {
        if (string.IsNullOrWhiteSpace(location))
        {
            throw new Exception("No location included at initialization");
        }
        //parameter filtering
        userLocation = location;
    }
StfBln
  • 1,137
  • 6
  • 11
  • couldn't this be shortened up? userLocation = location ?? throw new Exception("No location included at initialization"); – Dakota Kincer Mar 13 '17 at 18:00
  • 1
    From a personal standpoint, I prefer to separate visually Argument validation and allocation. It is to be noted as well OP is looking for StringIsNullOrWhiteSpace not just null (i.e. ??) – StfBln Mar 13 '17 at 18:03
0
    public FSCServerLocator(string location)
    {
        //parameter filtering
        userLocation = location;
        if (string.IsNullOrWhiteSpace(userLocation))
        {
            throw new Exception("No location included at initialization");
        }
    }

or

    public FSCServerLocator(string location)
    {
        if (string.IsNullOrWhiteSpace(location))
        {
            throw new Exception("No location included at initialization");
        }
        //parameter filtering
        userLocation = location;
    }

You're trying to use the parameter of the object before you set it in your constructor. You can either set it first, or test based on the argument you intend to set it with.

Andrew
  • 1,544
  • 1
  • 18
  • 36