Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Convert String to Size

Tags:

c#

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??

like image 663
Ari Avatar asked Dec 21 '22 13:12

Ari


2 Answers

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.

like image 192
David Yaw Avatar answered Jan 06 '23 06:01

David Yaw


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!

like image 20
Guido McMaster Avatar answered Jan 06 '23 06:01

Guido McMaster