Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a class from a .cs file

Is it possible to load a class and create Instance of it from It's .cs file?

I want to open a custom class in a .cs file and create instance of it in my application

thanks

like image 890
Arian Avatar asked Nov 05 '11 05:11

Arian


People also ask

How do I use a .CS file?

CS files may be opened and edited with basic text editors, including Microsoft Notepad++ (bundled with Windows) or Apple TextEdit (bundled with macOS). However, plain text editors are not good options for editing the files since they do not support the syntax structure.

What is .CS file in C#?

What is a CS file? Files with . cs extension are source code files for C# programming language. Introduced by Microsoft for use with the . NET Framework, the file format provides the low-level programming language for writing code that is compiled to generate the final output file in the form of EXE or a DLL.

How do I run a .CS file in Visual Studio?

It is easier to: Run Visual studio -> Make a new C# console project. This makes a project with a simple Program. cs file. You can just copy/paste in that, and run the project my clicking F5.


2 Answers

in theory yes - it mainly depends on whether you have all dependencies available...

IF so you can use the built-in CSharpCodeProvider to compile the .cs- file to an assembly (can be purely in-memory if need be) and then use Reflection to create an instance/use a class from that assembly...

Since don't provide much detail I would suggest to checkout these links and come back with detail questions if some arrise:

  • http://support.microsoft.com/kb/304655/en-us
  • http://www.codeproject.com/KB/cs/codecompilation.aspx
  • http://www.digitalcoding.com/Code-Snippets/C-Sharp/C-Code-Snippet-Compile-C-or-VB-source-code-run-time.html
  • http://www.c-sharpcorner.com/UploadFile/mgold/CodeDomCalculator08082005003253AM/CodeDomCalculator.aspx
  • http://www.csharp-examples.net/reflection-examples/
  • http://csharp.net-tutorials.com/reflection/introduction/
  • http://www.codeproject.com/KB/cs/C__Reflection_Tutorial.aspx
  • http://www.dotnetperls.com/reflection-field
  • C# Reflection: How to get class reference from string?
  • http://msdn.microsoft.com/en-us/library/system.reflection.assembly.aspx
  • http://msdn.microsoft.com/en-us/library/system.type.aspx
like image 193
Yahia Avatar answered Oct 17 '22 05:10

Yahia


You can use Microsoft.CSharp.CSharpCodeProvider and System.CodeDom to execute code at runtime, there is an article about this code project here and here

like image 34
Vamsi Avatar answered Oct 17 '22 05:10

Vamsi