2

I was trying to play with custom attributes of c#.

And as a part of this, consider this scenario: I have my client class which gives me a string to hash and specifies the hashing algorithm using custom attributes.

I was able to come up to this but stuck up when how to retrieve the custom attribute value.

class HashAlgorithmAttribute : Attribute { private string hashAlgorithm; public HashAlgorithmAttribute(string hashChoice) { this.hashAlgorithm= hashChoice; } } [HashAlgorithm("XTEA")] class ClientClass { public static string GetstringToBeHashed() { return "testString"; } } class ServerClass { public void GetHashingAlgorithm() { var stringToBeHashed = ClientClass.GetstringToBeHashed(); ///object[] hashingMethod = typeof(HashAlgorithm).GetCustomAttributes(typeof(HashAlgorithm), false); } } 
0

1 Answer 1

2

Using mocked up example of your attribute class:

[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)] sealed class HashAlgorithmAttribute : Attribute { readonly string algorithm; public HashAlgorithmAttribute(string algorithm) { this.algorithm = algorithm; } public string Algorithm { get { return algorithm; } } } 

And test class:

[HashAlgorithm("XTEA")] class Test { } 

To get value:

var attribute = typeof(Test).GetCustomAttributes(true) .FirstOrDefault(a => a.GetType() == typeof(HashAlgorithmAttribute)); var algorithm = ""; if (attribute != null) { algorithm = ((HashAlgorithmAttribute)attribute).Algorithm; } Console.WriteLine(algorithm); //XTEA 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.