Calling Constructor conditionally

K

Karthik D V

Is there any way to call the base class constructor conditionally.

For Example

class Shape
{
public Shape(int x)
{

}
}

class Rectangle : Shape
{
Shape(int x, int y) : base(x)
{

}
}

This works fine...

But what if i need something like this ??

class Rectangle : Shape
{
Shape(int x, int y)
{
if( x > y) //Some condition
{
// How Do I pass x value to base class here.?
}
}
}

As for as i know this is not possible. Am I right here????
 
G

Guest

You can either create an initialization method that you call from the
constructor, or you can do the following:

class Base
{
public Base(int x)
{
}
}

class Derived : Base
{
public Derived(int x, int y)
: base((x < y) ? x : y)
{
}
}

Mark
 
K

Karthik D V

Hi Mark R. Dawson,

If condition doesn't satisfies , i dont want to call the base
class constructor.

Well thanks for reply.
 
J

Jon Skeet [C# MVP]

Karthik D V said:
If condition doesn't satisfies , i dont want to call the base
class constructor.

You can't do that. You'd have to have a static method which determined
what you wanted to do, and then called one of a range of Derived class
constructors which did the appropriate thing.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top