Codedom is it limitations?features?

Posted: May 16, 2005 in Uncategorized

While replying to a post on .netindiagroup I found the codedom has pretty strange behavior and quite a few limitation are incorporate with the same.First the question asked was why it simply can’t create a signature of method like

public rettype funcname() {}

even though u passed the members attribute as public it generates

public virtual rettype funcname(){}

Further if u need 2 attributes let say protected internal …

here are other limitation for codedom:-(From BCL team BLOG)

note :we can use the syntax property.attribute=memberattribute.attribute1 | memberattributes.attrib2 as well for defining 2 attributes for the method sig.

Here is the answer to generate a public signature

property.Attributes = (property.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public ;

(thanks to vinay bhusan gattam redyy and Ms peoples liek the Yiru,joel pobar,KitG to correct me).

sample codedom to create a class on the fly:-

//generate a strem to write with

Stream cFile = File.Open(@"C:\Documents and Settings\shdash\Desktop\sample.cs", FileMode.Create);

StreamWriter sw = new StreamWriter(cFile);

//generate a csharp provider and a codegenerator and codesnippetcompileunit

CSharpCodeProvider provider=new CSharpCodeProvider();

ICodeGenerator codegen=provider.CreateGenerator(sw);

CodeGeneratorOptions codegenopt=new CodeGeneratorOptions();

CodeSnippetCompileUnit snippetunit=new CodeSnippetCompileUnit("using System");


//craete name spaces and class and teh class to namespace

CodeNamespace namespc=new CodeNamespace("samplecodedomnamespace");

CodeTypeDeclaration clsdec=new CodeTypeDeclaration();


clsdec.IsClass =true;


//add a constructor to the class


CodeConstructor constr=new CodeConstructor();



//add a public member field to the class

CodeMemberField clsmem=new CodeMemberField();



clsmem.Type =new CodeTypeReference("System.String");

clsdec.Members.Add (clsmem);

//add a properety to the class

CodeMemberProperty property = new CodeMemberProperty();

property.Name = "dynpop";

property.Type = new CodeTypeReference("System.String");


property.GetStatements.Add( new CodeMethodReturnStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "dynpop") ) );

property.SetStatements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),"dynpop"), new CodePropertySetValueReferenceExpression()));


//generate the code





Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s