New VS Init

In dynamic object, we can use New to create object. And it support parameters too.

public abstract class User : DbObjectModel<User>
{
    public abstract string Name { get; set; }
    public abstract int Age { get; set; }
    public User() {}
    public User(string Name, int Age)
    {
    	this.Name = Name;
    	this.Age = Age;
    }
}

To create new object by parameters:

User u = DynamicObject.NewObject<User>("tom", 18);

This looks very good, but it has 2 defects:
  1. No intellisense of parameters
  2. Can’t pass null
Instead, we can define the Init function to replace the constructor which have parameters:

public abstract class User : DbObjectModel<User>
{
    public abstract string Name { get; set; }
    public abstract int Age { get; set; }
    public abstract User Init(string Name, int Age);
}

To create new object by parameters:

User u = User.New.Init("tom", 18);

A little longer, but fully support intellisense and can pass null too.

I think it is a better way to create dynamic object.

Last edited Jun 30, 2009 at 5:20 AM by lifeng, version 2

Comments

lifeng Sep 8, 2009 at 1:29 PM 
Thanks for your comment.
This article didn't need for the recent source code anymore.
You can just ignore it if you are using the recent source code.

javafun Sep 7, 2009 at 12:30 PM 
The above example no longer works, can you update the example?