Set a default value to a property

No, there is no built-in way to set the value of a property with metadata. You could use a factory of some sort that would build instances of a class with reflection and then that could set the default values. But in short, you need to use the constructors (or field setters, which are lifted …

Read more

How can I determine property types using reflection?

What type are you interested in? The return type of the method/property/event etc? If so, I don’t think there’s anything in MemberInfo to let you get at it directly – you’ll need to cast and use MethodInfo.ReturnType, PropertyInfo.PropertyType, FieldInfo.FieldType, EventInfo.EventHandlerType and any others I’ve forgotten. (Remember that types themselves can be members. Not sure what …

Read more

How to get the current user’s Active Directory details in C#

The “pre Windows 2000” name i.e. DOMAIN\SomeBody, the Somebody portion is known as sAMAccountName. So try: using(DirectoryEntry de = new DirectoryEntry(“LDAP://MyDomainController”)) { using(DirectorySearcher adSearch = new DirectorySearcher(de)) { adSearch.Filter = “(sAMAccountName=someuser)”; SearchResult adSearchResult = adSearch.FindOne(); } } [email protected] is the UserPrincipalName, but it isn’t a required field.

Create a cryptographically secure random GUID in .NET

Yes you can, Guid allows you to create a Guid using a byte array, and RNGCryptoServiceProvider can generate a random byte array, so you can use the output to feed a new Guid: public Guid CreateCryptographicallySecureGuid() { using (var provider = new RNGCryptoServiceProvider()) { var bytes = new byte[16]; provider.GetBytes(bytes); return new Guid(bytes); } }

event.Invoke(args) vs event(args). Which is faster?

Writing someDelegate(…) is a compiler shorthand for someDelegate.Invoke(…). They both compile to the same IL—a callvirt instruction to that delegate type’s Invoke method. The Invoke method is generated by the compiler for each concrete delegate type. By contrast, the DynamicInvoke method, defined on the base Delegate type, uses reflection to call the delegate and is …

Read more