Reputation: 520
I have a method for converting text to bitmap:
private Bitmap ConvertTextToImage(string text, FontFamily fontFamily, float fontSize, FontStyle fontStyle,
StringFormat stringFormat, float MaxWidth, float MaxHeight, Color backgroundColor, Color foregroundColor)
{
// some code...
}
I want to make all parameters optional except text
, fontFamily
and fontSize
. However, I have no idea how to create a compile-time constant StringFormat
. I want it to be like a new StringFormat()
by default.
Upvotes: 1
Views: 132
Reputation: 109792
In your case you can let null
be the default value and then check for null
and replace it with the value that you do want for the default.
This is easier to demonstrate with an example:
private Bitmap ConvertTextToImage(string text, FontFamily fontFamily, float fontSize, FontStyle fontStyle,
StringFormat stringFormat = null, float MaxWidth = 10, float MaxHeight = 10, Color backgroundColor = default, Color foregroundColor = default)
{
if (stringFormat == null)
stringFormat = new StringFormat(); // Or whatever default you want.
// some code...
}
Alternatively (and in many cases more flexible) have an overload that takes ALL the parameters, and then provide additional overloads with missing parameters that call the version with all the parameters, passing appropriate values for the missing parameters:
private Bitmap ConvertTextToImage(string text, FontFamily fontFamily, float fontSize, FontStyle fontStyle,
float MaxWidth, float MaxHeight, Color backgroundColor, Color foregroundColor)
{
return ConvertTextToImage(text, fontFamily, fontSize, fontStyle, new StringFormat(), MaxWidth, MaxHeight, backgroundColor, foregroundColor);
}
For your example, I think this second approach would be easier, since you have some other parameters (the Color
ones) which cannot have a default value other than by using the default
keyword.
If you want to check those values, do the following sort of thing in the constructor:
if (backgroundColor == default)
backgroundColor = Color.Beige; // Who doesn't love beige?
This only works if you NEVER want to pass a colour with RGB and transparency values all zero, since that's what the default for Color
is.
Upvotes: 2
Reputation: 22119
You could assign null
or default
and initialize stringFormat
inside the method.
private Bitmap ConvertTextToImage(string text, FontFamily fontFamily, float fontSize, FontStyle fontStyle,
StringFormat stringFormat = default, float MaxWidth = default, float MaxHeight = default, Color backgroundColor = default, Color foregroundColor = default)
{
if (stringFormat == null)
stringFormat = new StringFormat();
// ...other code.
}
Upvotes: 1