Reputation: 5
public Alphabet(params char[] list)
{
this.ExceptionInitializer();
try
{
if (list != null) _alphabet = list;
else throw this.NullableAssignment; //add exception handler;
this._charCounter = list.Length;
}
catch (this.NullableAssignment)
{
// var x = new Alphabet();
// this = x; //FAIL!
}
}
Upvotes: 0
Views: 100
Reputation: 4745
The code you are proposing is not valid in C#, you cannot assign any value to this. What you could do is to use a call to a default constructor like this:
public Alphabet() { /* Do some default initialization here */ }
public Alphabet(params char[] list) : this() // The call to the default constructor.
{
if (list != null)
{
_alphabet = list;
this._charCounter = list.Length;
}
}
Upvotes: 2
Reputation: 14162
public Alphabet() {
ConstructEmptyAlphabet();
}
public Alphabet(char[] list) {
if (list == null) {
ConstructEmptyAlphabet();
} else {
_alphabet = list;
this._charCounter = list.Length;
}
}
private void ConstructEmptyAlphabet() {
…
}
Upvotes: 0
Reputation: 284796
I don't know what you're trying to do. Can you show ExceptionInitializer and NullableAssignment? Do you want to assign an empty array to _alphabet
when no parameters are passed in?
public Alphabet(params char[] list)
{
if(list != null)
{
_alphabet = list;
}
else
{
_alphabet = new char[0];
}
this._charCounter = _alphabet.Length;
}
This will work for any number of arguments, or an explicit null:
new Alphabet('f', 'o', 'o')
new Alphabet()
new Alphabet(null)
Upvotes: 0
Reputation: 144136
You can't do this - the closest thing would be to create a static factory method which returns an Alphabet
:
public class Alphabet
{
private Alphabet(params char[] list)
{
//setup
}
public static Alphabet Create(params char[] list)
{
return list == null
? new Alphabet()
: new Alphabet(list);
}
}
Although given your example, even simpler would just be to assign an empty array in the place of null:
public Alphabet(params char[] list)
{
_alphabet = list ?? new char[] { };
this._charCounter = _alphabet.Length;
}
Upvotes: 0
Reputation: 41378
I'm guessing that you want the constructor for Alphabet
to process the elements of list
, unless list
is empty in which case a special "empty object" should be used. This, unfortunately, can't be accomplished using a normal constructor. What you need instead is a factory method:
private static Alphabet _emptyAlphabet = new Alphabet();
private Alphabet(char[] list) { /* etc */ }
public Alphabet CreateAlphabet(params char[] list)
{
if (list == null)
{
return _emptyAlphabet;
}
else
{
return new Alphabet(list);
}
}
Upvotes: 0