The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

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 (483) [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...