Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# 4 Optional Null EventHandler

I am attempting to write a method that has an optional EventHandler Paramater. it currently looks like this:

public void AddItemToMainMenu(MenuItem parentMenu, MenuItems item, String menuItemText, bool isChecked, EventHandler? eventHandler = null)

the error occurs on the last argument, it states:

Error 51 The type 'System.EventHandler' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable'

EDIT: I have removed the ? and now receive a very similar error, I also made an unimportant change to another argument. it now reads as follows:

 public void AddItemToMainMenu( MenuItems item, String menuItemText, bool isChecked, EventHandler eventHandler = null, MenuItem? parentMenu = null)

Error 41 The type 'System.EventHandler' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable'

like image 420
jth41 Avatar asked Feb 24 '26 18:02

jth41


2 Answers

EventHandler is a reference type, therefore is inherently nullable. Should be:

public void AddItemToMainMenu(MenuItem parentMenu, MenuItems item, String menuItemText, bool isChecked, EventHandler eventHandler = null)
like image 73
Marcel N. Avatar answered Feb 27 '26 13:02

Marcel N.


You don't need to make EventHandler nullable. Remove the ? in the definition.

The exception says System.EventHandler must be a non-nullable value type. Since EventHandler is a class, or reference type, it obviously cannot be a value type and is, by convention nullable.

like image 27
IAbstract Avatar answered Feb 27 '26 14:02

IAbstract



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!