Insert portion of code from another file
.Net 2.0
Previously using C++, we could use #include <filename> and the contents of that file would be dropped where the #include was specified. I am looking for something similar.
Example:
Code:
public void A()
{
string output = string.Empty;
for (int i = 0; i < 5; ++i)
{
#include <somefile>
output += i;
output += "\n";
}
MessageBox.Show(output);
}
somefile's contents:
i++;
So the output should be:
1
3
5
I can do it using reflection and partial classes but I really dont want to do it this way. Its long and clumsy.
Thanks in advance.
Re: Insert portion of code from another file
Re: Insert portion of code from another file
#include is not allowed in .NET. Why would you want to do that?
Re: Insert portion of code from another file
If you realy want, you can add an existing file as a link in Visual Studio, meaning it exist in only one copy on the disk, but is referenced multiple times from more then one projec, but why would you do it this way? Place the shared code in class in class library and reference the assembly from whereever you want.
Re: Insert portion of code from another file
Thanks for your replies. Its not shared code, it is code added further down the implementation line by another group. Unfortunately, #if doesnt work for this specific example either. What I am thinking we need to do is something like this (which I dont really like) :
Code:
// Program.cs
namespace ConsoleApplication1
{
partial class Program
{
public void A()
{
string output = string.Empty;
for (int i = 0; i < 5; ++i)
{
Type[] t = new Type[1];
t.SetValue(i.GetType(), 0);
Assembly assm = Assembly.GetExecutingAssembly();
Type type = assm.GetType("ConsoleApplication1.Program");
MethodInfo mi = type.GetMethod("A1", t);
if (mi != null)
{
object a = mi.Invoke(this, new object[] { i });
i = Convert.ToInt32(a);
}
output += i;
output += "\n";
}
MessageBox.Show(output);
}
static void Main(string[] args)
{
Program p = new Program();
p.A();
}
}
}
//CodeFile1.cs
namespace ConsoleApplication1
{
partial class Program
{
public int A1(int i)
{
return ++i;
}
}
}
By doing it this way CodeFile1.cs file doesnt have to exist and can be dropped in later.