Click to See Complete Forum and Search --> : Insert portion of code from another file
SSix2
April 1st, 2009, 05:31 PM
.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:
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.
Mutant_Fruit
April 1st, 2009, 05:45 PM
You can't do this.
Shuja Ali
April 2nd, 2009, 03:05 AM
#include is not allowed in .NET. Why would you want to do that?
boudino
April 2nd, 2009, 07:27 AM
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.
SSix2
April 2nd, 2009, 08:58 AM
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) :
// 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.
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.