ARTICLE AD BOX
SubjectAlternativeNameBuilder doesn't provide a method to add Registered Id attribute so, I'm trying to use reflection to achieve my goal:
var assembly = typeof(SubjectAlternativeNameBuilder).Assembly; var generalNameAsnType = assembly.GetType("System.Security.Cryptography.Asn1.GeneralNameAsn"); var generalNameAsn = Activator.CreateInstance(generalNameAsnType); generalNameAsnType.GetField("RegisteredId", BindingFlags.Instance | BindingFlags.NonPublic) .SetValue(generalNameAsn, "1.3.6.1.4.1.311.20.2.3"); var methodInfo = typeof(SubjectAlternativeNameBuilder).GetMethod("AddGeneralName"); var san = new SubjectAlternativeNameBuilder(); methodInfo.Invoke(san, \[generalNameAsn\]);But I'm getting NullReferenceException at the last line. And for some reason I can't debug into methodInfo.Invoke. If I try I see the following

How can I call this method with reflection?
19.4k12 gold badges68 silver badges119 bronze badges
9
The first bug I can see is: the method you are looking for AddGeneralName does not exist, or it is non-public. But you are looking for this method as it was public, because the default for System.Type.GetMethod is the public access. Therefore, it should return null.
Please see https://learn.microsoft.com/en-us/dotnet/api/system.type.getmethod.
This is just one issue you can easily fix using System.Reflection.BindingFlags. There could be other issues.
However, please pay close attention for my and other comments. I understand if you are interested just in the Reflection techniques. Usually, you apply Reflection to your own code. A typical use case is a plugin system.
But the code with that method is not your code. In particular, it means that the method you mentioned is not designed to be called. So, depending on your purpose, you have to do something else, without breaking the access system of this API.
Explore related questions
See similar questions with these tags.
