Class Fields

D

DaveL

How Can i Determine if a class Contains a Particular
Field Variable

Example
public class AbastractClass
{
public int Field1
public int Field2
}
public Class Class1:AbstractClass
{
public int Specificfield
}
public Class Class2:AbstractClass
{
public int SpecificField
public int NewField
}
public class MainClass
{
int condition = 1

AbstractClass oJob
if (condition==1)
{
oJob = new Class1()
}
else
{
oJob = new Class2()
}
///how to find if ojob has a field "NewFiled"

}
 
P

pagerintas pritupimas

Something like that:

Class2 class2 = oJob as Class2;
if (class2 != null)
{
Console.WriteLine(class2.NewField);
}

Or you could use reflection. Although these are solutions to the wrong
problem. The real problem is design.
 
D

DaveL

if u notice in my example the class that created the 2
Classes Class1 and class2 ,has no idea of which is which
if (condition==1) then ojob is class1
else then ojob is class2

//processing code
if ojob.NewField==10) //Crash if ojob is Class1


Thanks Dave
 
M

Mel Weaver

Just cast it like Jon said

private void RunJob(AbstractClass oJob)
{
Class2 c = oJob as Class2;
if (c != null)
{
// then set your value;
}
}

// or using reflection
using System.Reflection;
private void RunJob(AbstractClass oJob)
{
PropertyInfo propertyInfo =
oJob.GetType().GetProperty("EnterFieldName");
if (propertyInfo != null)
{
// then set your value;
}
}
 
D

DaveL

thanks Mel, thats what i need cause the code im repairing
the method involved dont know about the missing value
but must use it if present

Thanks Alot
Dave
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top