You can't. Bear in mind that foo
is a variable of type string
.
You could create your own type, say BoundedString
, and have:
BoundedString foo = new BoundedString(5);
foo.Text = "hello"; // Fine
foo.Text = "naughty"; // Throw an exception or perhaps truncate the string
... but you can't stop a string variable from being set to any string reference (or null).
Of course, if you've got a string property, you could do that:
private string foo;
public string Foo
{
get { return foo; }
set
{
if (value.Length > 5)
{
throw new ArgumentException("value");
}
foo = value;
}
}
Does that help you in whatever your bigger context is?