0

I need an instance of the same class as another object, but I don't know the exact type. I have the following code.

abstract public class Row{
     .
     .
     .
}

public class User : Row{
    .
    .
    .
}
.
.
.
.
User test = new User();
Open(test);
.
.
.

private Row backup;

public static void Open(Row row){
    .
    .
    .
    db.backup = (Row) Activator.CreateInstance(row.GetType());
    .
    .
    .
}

But when I run the program it generates NullReferenceException and I don't understand why... I tested it on the debugger and "row" is not null, everything seems right.

I googled it but no luck... however I read comments of people complaining about Activator.CreateInstance being too slow... is that true? what the best way to do this job?

10
  • 2
    Your code doesn't compile - you are accessing an instance member (backup) from a static method (Open). What is the exact exception you get (and on what line)
    – D Stanley
    Commented Feb 20, 2014 at 22:53
  • I have similar code working with no problems. Can you provide more info from the exception? Stacktrace and which line you posted throws it would be good. Commented Feb 20, 2014 at 22:55
  • What do you plan to do once you create a User object? Commented Feb 20, 2014 at 22:55
  • @DStanley: Sorry it actually says: db.backup, so it does compile
    – george b
    Commented Feb 20, 2014 at 22:56
  • 2
    @georgeb is db null?
    – D Stanley
    Commented Feb 20, 2014 at 23:02

1 Answer 1

0

Sorry it was my mistake... as D Stanley correctly pointed out db was null, and that's the reason why the program threw an exception.

1
  • Glad you figure it out - for future reference the debugger is a GREAT tool to weed out such errors. And it doesn't hurt to add null-check to your code wither.
    – D Stanley
    Commented Feb 20, 2014 at 23:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.