Modifying type-specific properties in implementation of interface
-
22-09-2019 - |
Question
I know this is a silly question, in that the answer is likely an "oh right, of course!" one.
Here is what I have:
public interface IEvent {
int Id
string Title
}
public class MeetingEvent : IEvent {
int Id
string Title
//Meeting Properties
string Room;
User Organizer;
}
public class BirthdayEvent : IEvent {
int Id
string Title
//Bday Properties
int Candles;
bool Surprise;
}
I am working on a custom model binder in ASP.NET MVC as my main edit form inherits from IEvent while I perform a RenderPartial to add the other type-specific fields
When I get to the model binder, I can see all the keys/values for the type, which is good. Now, I want to do this:
IEvent _event;
switch (eventType) { // EventType is an enum
case EventType.Birthday:
_event = new BirthdayEvent();
_event.Candles= GetValue<int>(bindingContext, "Candles");
_event.Surprise= GetValue<bool>(bindingContext, "Surprise");
break;
case EventType.Meeting:
_event = new MeetingEvent();
// Meeting-specific fields are set here...
break;
default:
throw new InvalidOperationException("Invalid Event Type");
}
In essence, I want an IEvent variable and I want to create a specific event type that implements IEvent and set the type-specific fields. What Visual Studio tells me is that it can not access the BirthdayEvent fields.
While, I understand this, I can't seem to figure out what I need to do. Thus, this question :).
Thanks in advance!
Solution
When you first create your instances of BirthdayEvent
and MeetingEvent
, put them in variables of that type. That way you can assign those members. Then assign them to your _event
variable. Like this:
switch (eventType) { // EventType is an enum
case EventType.Birthday:
{
var be = new BirthdayEvent();
be.Candles= GetValue<int>(bindingContext, "Candles");
be.Surprise= GetValue<bool>(bindingContext, "Surprise");
_event = be;
break;
}
case EventType.Meeting:
{
var me = new MeetingEvent();
// Meeting-specific fields are set here...
_event = me;
break;
{
default:
throw new InvalidOperationException("Invalid Event Type");
}
OTHER TIPS
Something along these lines:
IEvent _event;
switch (eventType) { // EventType is an enum
case EventType.Birthday:
var birthdayEvent = new BirthdayEvent();
birthdayEvent.Candles= GetValue<int>(bindingContext, "Candles");
birthdayEvent.Surprise= GetValue<bool>(bindingContext, "Surprise");
_event = birthdayEvent;
break;
/* etc */
default:
throw new InvalidOperationException("Invalid Event Type");
}