Jiang (6) [Avatar] Offline
#1
I know what the code does, but "where T: new()" is just killing me. I didn't know that you can pull that off.

public static T MarshalObject<T>(FormView f) where T:new()
{
T dto = new T();
Type type = dto.GetType();
for (int i = 0; i < f.Row.Cells[0].Controls.Count; i += 2)
{
Control label = f.Row.Cells[0].Controls[i];
if (label is LiteralControl)
{
string propName = (label as LiteralControl).Text;
propName = Regex.Replace(propName, "([\s:-]*(<br[ ]*/>smilie*)(\w+)([\s:-])+", "$3");
if (!String.IsNullOrEmpty(propName))
{
PropertyInfo prop = GetProperty(propName, type);
if (prop != null)
{
Control valueCell = f.Row.Cells[0].Controls[i + 1];
object value = (valueCell is TextBox)
? (valueCell as TextBox).Text
: null;
prop.SetValue(dto, value, null);
}
}
}
}
return dto;
}
tomten (19) [Avatar] Offline
#2
Re: A piece of code that is very interesting--the code is not from the book...
> I know what the code does, but "where T: new()" is
> just killing me. I didn't know that you can pull
> that off.

http://msdn.microsoft.com/en-us/library/d5x73970.aspx
Jiang (6) [Avatar] Offline
#3
Re: A piece of code that is very interesting--the code is not from the book...
Thanks!

I should have got that by googling for "T: new()"
tomten (19) [Avatar] Offline
#4
Re: A piece of code that is very interesting--the code is not from the book...
> I should have got that by googling for "T: new()"

Well, it's always hard to google for short words, code snippets etc. The whole C# Programming Guide is very good; I can recommend reading it:

http://msdn.microsoft.com/en-us/library/67ef8sbd.aspx
jon.skeet (451) [Avatar] Offline
#5
Re: A piece of code that is very interesting--the code is not from the book...
> I know what the code does, but "where T: new()" is
> just killing me. I didn't know that you can pull
> that off.

As well as tomten's reply, see page 76/77, "Constructor type constraints" in the book smilie

Jon
Jiang (6) [Avatar] Offline
#6
Re: A piece of code that is very interesting--the code is not from the book...
Thanks, Jon. Yes, it's right there. There is too much to catch up, too little time.

C# 3.0, asp.net 3.5, ajax, asp.net MVC framework, Entity Framework, the list goes on and on...