Welcome to Dream.In.Code
Getting C# Help is Easy!

Join 131,549 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 2,231 people online right now. Registration is fast and FREE... Join Now!




Validate instance of class in contructor before creation

 
Reply to this topicStart new topic

Validate instance of class in contructor before creation

ragingben
post 8 Oct, 2008 - 02:52 AM
Post #1


New D.I.C Head

*
Joined: 7 Oct, 2008
Posts: 30


My Contributions


Ok heres a question that I hope some of you C# gurus will be able to answer pretyy easily.

I want to create a new instance of a class with 1 argument (custom enumeration) in in the constructor. The constructor then checks to see if this instance is legal by seeing if the argument is within an array of legal instances. If it is not, I don't want the instance of the class to be created. I know this would easy to do in the code for the main program by checking the validity before creating the new instance, but I don't wan't it to be checked there!

Any ideas?

CODE

    public class Stepper : Axis
    {
        /// <summary>
        /// Create a new stepper motor for a specified axis
        /// </summary>
        /// <param name="axis"></param>
        public Stepper(EStepperAxis proposedAxis)
        {
            Boolean axisAvailable = false;

            // look at all the elements in static array to see if axis is available
            for (Int32 index = 0; index < Stepper.availableAxis.Length; index++ )
            {
                // if found then update boolean
                if (Stepper.availableAxis[index] == proposedAxis)
                {
                    axisAvailable = true;
                }
            }

            // if the axis is avaiable
            if (axisAvailable == true)
            {
                // assign axis
                this.axis = proposedAxis;
                // remove from list
                Stepper.availableAxis[(Int32)proposedAxis] = null;
                // display message
                Console.WriteLine("Axis {0} has been assigned to {1}", proposedAxis, this);
            }
            else
            {
                // display message
                Console.WriteLine("Could not create a new axis {0}: Axis not available.", proposedAxis);
                
                // THIS IS WHERE IT SHOULD ABORT CREATING INSTANCE!!!
            }

        }
User is offlineProfile CardPM

Go to the top of the page


baavgai
post 8 Oct, 2008 - 04:49 AM
Post #2


Dreaming Coder

Group Icon
Joined: 16 Oct, 2007
Posts: 1,945



Thanked 94 times

Dream Kudos: 475

Expert In: C, C++, Java, C#, ASP.NET, PHP, Perl, Python, Oracle, SQL Server, MySql, HTML, JavaScript, Lua

My Contributions


One way would be to place an exception in the constructor:
csharp

class Widget {
private string name;
private int grams;
public Widget(string name, int grams) {
if (grams < 1) {
throw new System.ArgumentException("Grams cannot be less than 1.");
}
this.name = name;
this.grams = grams;
}


Another would be to place an "IsValid" flag in the object.

You could also use something called a factory pattern, where another object provides instances for you and no other object can. Though you implied you didn't want that.

A variation on the factory is to allow the object itself to handle the creation on instances external to the constructor. This allows for some extra failover behavior, including just returning null. Here's an example of that:
csharp

class Widget {
private string name;
private int grams;
// private constructor
// no one other than me can create an instance
private Widget() { }
public string Name { get { return this.name; } }
public int Grams { get { return this.grams; } }
public override string ToString() {
return "Widget: " + this.name + ", " + this.grams + "g";
}

// one of the few times I'd ever use static
public static Widget GetNew(string name, int grams) {
// we don't have to throw errors
// just send back a null object.
if (grams < 1) { return null; }

Widget obj = new Widget();
obj.name = name;
obj.grams = grams;
return obj;
}
}
User is offlineProfile CardPM

Go to the top of the page

Fast ReplyReply to this topicStart new topic
Time is now: 11/20/08 02:26AM

Live C# Help!

C# Tutorials

Reference Sheets

C# Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month