Hey is there a way to convert a string variable to the datatype Size?
for example, if I had this variable
string tempSize;
how could I convert that to a dataType Size for reading purposes??
Which Size are you referring to?
If you mean System.Windows.Size, there is a Size.Parse(string) method.
If you mean System.Drawing.Size, there's no built in parse method, you'll have to parse the string yourself.
We're talking about the System.Drawing.Size struct as used in Winforms, yes?
As noted above, this struct doesn't have a Parse() function. So you gotta do it yourself. One option is just to format and parse a string of your own devising:
// format a custom string to encode your size
string mySizeString = string.Format("{0}:{1}", mySize.Width, mySize.Height);
// parse your custom string and make a new size
string[] sizeParts = mySizeString.Split(':');
int height = int.Parse(sizeParts[0]);
int width = int.Parse(sizeParts[1]);
Size mySize = new Size(height, width);
Another alternative is to use the TypeConverter class to do to formatting and parsing for you:
// convert a Size to a string using a type converter
TypeConverter tc = TypeDescriptor.GetConverter(typeof(Size));
string mySizeString = tc.ConvertToString(mySize);
// convert a string to a Size using a type converter
TypeConverter tc = TypeDescriptor.GetConverter(typeof(Size));
Size mySize = (Size)tc.ConvertFromString(mySizeString);
Perhaps this last solution is just the right size for you (har har). In any case I'm sure some clever person has written extension functions to extend the Size struct in this way. That would be nifty!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With