C# add const field using attributes












0















We have class 'SomeClass':



namespace Namespace
{
class SomeClass
{
// something
}
}


And attribute 'SomeAttribute':



class SomeAttribute : System.Attribute { }


Task: add to all classes market by SomeAttribute 'public const string Type' field. Modified classes must be following:



class SomeClass
{
// something
public const string Type = @"Namespace.SomeClass";
}


UPD:



I'm using following approach for message transaction:



class Manager
{
// message has 3 parts:
// string message = String.Format("{0}{1}{2}",
// typeof(SomeClass).ToString(),
// splitter,
// Manager.Serialize(someClassObj)
// )
public static string GetType(string message) { /* some code */ }
public static string Serialize(SomeClass message) { /* XML serialization */ }
public static SomeClass Deserialize(string message) { /* deserialization */ }
}

class Logic
{
public void ProcessMessage(string message)
{
switch (Manager.GetType(message))
{
case SomeClass.Type:
{
SomeClass msg = Manager.Deserialize(message) as SomeClass;
// send message to binded objects
}
break;
case ClassInheritedFromSomeClass.Type:
{
// the same
}
break;
// etc.
}
}
}


UPD 2:



More about messages. At this time I'm using next approach:



public class BaseMessage
{
public const string Type = @"Messages.BaseMessage";
}

public class LoginMessage : BaseMessage
{
public new const string Type = @"Messages.Client.LoginMessage";

public string Nickname { get; set; }
public string Password { get; set; }
}


Conclusion



I think best case is to modify Manger like this:



class Manager
{
// create event table

public Action<BaseMessage> this[string eventName]
{
get
{
if (!m_eventTable.ContainsKey(eventName))
{
m_eventTable.Add(eventName, new Action<BaseMessage>(message => { }));
}
return m_eventTable[eventName];
}
set
{
m_eventTable[eventName] = value;
}
}

public void Send(BaseMessage message, string messageName)
{
if (m_eventTable.ContainsKey(messageName) && this[messageName].Method != null)
{
this[messageName].Invoke(message);
}
}

private Dictionary<string, Action<BaseMessage>> m_eventTable = new Dictionary<string, Action<BaseMessage>>();
}









share|improve this question




















  • 1





    why would you need that? typeof(SomeClass) is much more versatile...? For example typeof(SomeClass).FullName

    – Marc Gravell
    May 3 '12 at 13:26













  • And if the value of the constant is different from typeof(SomeClass).FullName: Why not put the value directly in the attribute?

    – dtb
    May 3 '12 at 13:28













  • Attributes are Reflection stuff. What you need might be more like a property in a base class returning GetType().FullName.

    – fero
    May 3 '12 at 13:29











  • I know about that case, but I use 'Type' in switch statement that required const values.

    – outoftime
    May 3 '12 at 13:49











  • In that case, I'd suggest that you should replace the switch with if/else statements.

    – Tim S.
    May 3 '12 at 13:53
















0















We have class 'SomeClass':



namespace Namespace
{
class SomeClass
{
// something
}
}


And attribute 'SomeAttribute':



class SomeAttribute : System.Attribute { }


Task: add to all classes market by SomeAttribute 'public const string Type' field. Modified classes must be following:



class SomeClass
{
// something
public const string Type = @"Namespace.SomeClass";
}


UPD:



I'm using following approach for message transaction:



class Manager
{
// message has 3 parts:
// string message = String.Format("{0}{1}{2}",
// typeof(SomeClass).ToString(),
// splitter,
// Manager.Serialize(someClassObj)
// )
public static string GetType(string message) { /* some code */ }
public static string Serialize(SomeClass message) { /* XML serialization */ }
public static SomeClass Deserialize(string message) { /* deserialization */ }
}

class Logic
{
public void ProcessMessage(string message)
{
switch (Manager.GetType(message))
{
case SomeClass.Type:
{
SomeClass msg = Manager.Deserialize(message) as SomeClass;
// send message to binded objects
}
break;
case ClassInheritedFromSomeClass.Type:
{
// the same
}
break;
// etc.
}
}
}


UPD 2:



More about messages. At this time I'm using next approach:



public class BaseMessage
{
public const string Type = @"Messages.BaseMessage";
}

public class LoginMessage : BaseMessage
{
public new const string Type = @"Messages.Client.LoginMessage";

public string Nickname { get; set; }
public string Password { get; set; }
}


Conclusion



I think best case is to modify Manger like this:



class Manager
{
// create event table

public Action<BaseMessage> this[string eventName]
{
get
{
if (!m_eventTable.ContainsKey(eventName))
{
m_eventTable.Add(eventName, new Action<BaseMessage>(message => { }));
}
return m_eventTable[eventName];
}
set
{
m_eventTable[eventName] = value;
}
}

public void Send(BaseMessage message, string messageName)
{
if (m_eventTable.ContainsKey(messageName) && this[messageName].Method != null)
{
this[messageName].Invoke(message);
}
}

private Dictionary<string, Action<BaseMessage>> m_eventTable = new Dictionary<string, Action<BaseMessage>>();
}









share|improve this question




















  • 1





    why would you need that? typeof(SomeClass) is much more versatile...? For example typeof(SomeClass).FullName

    – Marc Gravell
    May 3 '12 at 13:26













  • And if the value of the constant is different from typeof(SomeClass).FullName: Why not put the value directly in the attribute?

    – dtb
    May 3 '12 at 13:28













  • Attributes are Reflection stuff. What you need might be more like a property in a base class returning GetType().FullName.

    – fero
    May 3 '12 at 13:29











  • I know about that case, but I use 'Type' in switch statement that required const values.

    – outoftime
    May 3 '12 at 13:49











  • In that case, I'd suggest that you should replace the switch with if/else statements.

    – Tim S.
    May 3 '12 at 13:53














0












0








0


1






We have class 'SomeClass':



namespace Namespace
{
class SomeClass
{
// something
}
}


And attribute 'SomeAttribute':



class SomeAttribute : System.Attribute { }


Task: add to all classes market by SomeAttribute 'public const string Type' field. Modified classes must be following:



class SomeClass
{
// something
public const string Type = @"Namespace.SomeClass";
}


UPD:



I'm using following approach for message transaction:



class Manager
{
// message has 3 parts:
// string message = String.Format("{0}{1}{2}",
// typeof(SomeClass).ToString(),
// splitter,
// Manager.Serialize(someClassObj)
// )
public static string GetType(string message) { /* some code */ }
public static string Serialize(SomeClass message) { /* XML serialization */ }
public static SomeClass Deserialize(string message) { /* deserialization */ }
}

class Logic
{
public void ProcessMessage(string message)
{
switch (Manager.GetType(message))
{
case SomeClass.Type:
{
SomeClass msg = Manager.Deserialize(message) as SomeClass;
// send message to binded objects
}
break;
case ClassInheritedFromSomeClass.Type:
{
// the same
}
break;
// etc.
}
}
}


UPD 2:



More about messages. At this time I'm using next approach:



public class BaseMessage
{
public const string Type = @"Messages.BaseMessage";
}

public class LoginMessage : BaseMessage
{
public new const string Type = @"Messages.Client.LoginMessage";

public string Nickname { get; set; }
public string Password { get; set; }
}


Conclusion



I think best case is to modify Manger like this:



class Manager
{
// create event table

public Action<BaseMessage> this[string eventName]
{
get
{
if (!m_eventTable.ContainsKey(eventName))
{
m_eventTable.Add(eventName, new Action<BaseMessage>(message => { }));
}
return m_eventTable[eventName];
}
set
{
m_eventTable[eventName] = value;
}
}

public void Send(BaseMessage message, string messageName)
{
if (m_eventTable.ContainsKey(messageName) && this[messageName].Method != null)
{
this[messageName].Invoke(message);
}
}

private Dictionary<string, Action<BaseMessage>> m_eventTable = new Dictionary<string, Action<BaseMessage>>();
}









share|improve this question
















We have class 'SomeClass':



namespace Namespace
{
class SomeClass
{
// something
}
}


And attribute 'SomeAttribute':



class SomeAttribute : System.Attribute { }


Task: add to all classes market by SomeAttribute 'public const string Type' field. Modified classes must be following:



class SomeClass
{
// something
public const string Type = @"Namespace.SomeClass";
}


UPD:



I'm using following approach for message transaction:



class Manager
{
// message has 3 parts:
// string message = String.Format("{0}{1}{2}",
// typeof(SomeClass).ToString(),
// splitter,
// Manager.Serialize(someClassObj)
// )
public static string GetType(string message) { /* some code */ }
public static string Serialize(SomeClass message) { /* XML serialization */ }
public static SomeClass Deserialize(string message) { /* deserialization */ }
}

class Logic
{
public void ProcessMessage(string message)
{
switch (Manager.GetType(message))
{
case SomeClass.Type:
{
SomeClass msg = Manager.Deserialize(message) as SomeClass;
// send message to binded objects
}
break;
case ClassInheritedFromSomeClass.Type:
{
// the same
}
break;
// etc.
}
}
}


UPD 2:



More about messages. At this time I'm using next approach:



public class BaseMessage
{
public const string Type = @"Messages.BaseMessage";
}

public class LoginMessage : BaseMessage
{
public new const string Type = @"Messages.Client.LoginMessage";

public string Nickname { get; set; }
public string Password { get; set; }
}


Conclusion



I think best case is to modify Manger like this:



class Manager
{
// create event table

public Action<BaseMessage> this[string eventName]
{
get
{
if (!m_eventTable.ContainsKey(eventName))
{
m_eventTable.Add(eventName, new Action<BaseMessage>(message => { }));
}
return m_eventTable[eventName];
}
set
{
m_eventTable[eventName] = value;
}
}

public void Send(BaseMessage message, string messageName)
{
if (m_eventTable.ContainsKey(messageName) && this[messageName].Method != null)
{
this[messageName].Invoke(message);
}
}

private Dictionary<string, Action<BaseMessage>> m_eventTable = new Dictionary<string, Action<BaseMessage>>();
}






c# .net-assembly






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 18 '18 at 14:12









Cœur

18.1k9108148




18.1k9108148










asked May 3 '12 at 13:24









outoftimeoutoftime

600417




600417








  • 1





    why would you need that? typeof(SomeClass) is much more versatile...? For example typeof(SomeClass).FullName

    – Marc Gravell
    May 3 '12 at 13:26













  • And if the value of the constant is different from typeof(SomeClass).FullName: Why not put the value directly in the attribute?

    – dtb
    May 3 '12 at 13:28













  • Attributes are Reflection stuff. What you need might be more like a property in a base class returning GetType().FullName.

    – fero
    May 3 '12 at 13:29











  • I know about that case, but I use 'Type' in switch statement that required const values.

    – outoftime
    May 3 '12 at 13:49











  • In that case, I'd suggest that you should replace the switch with if/else statements.

    – Tim S.
    May 3 '12 at 13:53














  • 1





    why would you need that? typeof(SomeClass) is much more versatile...? For example typeof(SomeClass).FullName

    – Marc Gravell
    May 3 '12 at 13:26













  • And if the value of the constant is different from typeof(SomeClass).FullName: Why not put the value directly in the attribute?

    – dtb
    May 3 '12 at 13:28













  • Attributes are Reflection stuff. What you need might be more like a property in a base class returning GetType().FullName.

    – fero
    May 3 '12 at 13:29











  • I know about that case, but I use 'Type' in switch statement that required const values.

    – outoftime
    May 3 '12 at 13:49











  • In that case, I'd suggest that you should replace the switch with if/else statements.

    – Tim S.
    May 3 '12 at 13:53








1




1





why would you need that? typeof(SomeClass) is much more versatile...? For example typeof(SomeClass).FullName

– Marc Gravell
May 3 '12 at 13:26







why would you need that? typeof(SomeClass) is much more versatile...? For example typeof(SomeClass).FullName

– Marc Gravell
May 3 '12 at 13:26















And if the value of the constant is different from typeof(SomeClass).FullName: Why not put the value directly in the attribute?

– dtb
May 3 '12 at 13:28







And if the value of the constant is different from typeof(SomeClass).FullName: Why not put the value directly in the attribute?

– dtb
May 3 '12 at 13:28















Attributes are Reflection stuff. What you need might be more like a property in a base class returning GetType().FullName.

– fero
May 3 '12 at 13:29





Attributes are Reflection stuff. What you need might be more like a property in a base class returning GetType().FullName.

– fero
May 3 '12 at 13:29













I know about that case, but I use 'Type' in switch statement that required const values.

– outoftime
May 3 '12 at 13:49





I know about that case, but I use 'Type' in switch statement that required const values.

– outoftime
May 3 '12 at 13:49













In that case, I'd suggest that you should replace the switch with if/else statements.

– Tim S.
May 3 '12 at 13:53





In that case, I'd suggest that you should replace the switch with if/else statements.

– Tim S.
May 3 '12 at 13:53












1 Answer
1






active

oldest

votes


















0














Using switch with GetType is the wrong way to implement polymorphism, because it only checks the most-derived class (breaks extensibility).



In your particular case, where you want the Manager to be responsible for the behavior, you might use the dynamic keyword and overloaded methods. But this will again violate SOLID, because it isn't open for extension.



Instead of violating SOLID this way, try to find a way to use virtual methods to perform the type-specific action.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f10432352%2fc-sharp-add-const-field-using-attributes%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Using switch with GetType is the wrong way to implement polymorphism, because it only checks the most-derived class (breaks extensibility).



    In your particular case, where you want the Manager to be responsible for the behavior, you might use the dynamic keyword and overloaded methods. But this will again violate SOLID, because it isn't open for extension.



    Instead of violating SOLID this way, try to find a way to use virtual methods to perform the type-specific action.






    share|improve this answer




























      0














      Using switch with GetType is the wrong way to implement polymorphism, because it only checks the most-derived class (breaks extensibility).



      In your particular case, where you want the Manager to be responsible for the behavior, you might use the dynamic keyword and overloaded methods. But this will again violate SOLID, because it isn't open for extension.



      Instead of violating SOLID this way, try to find a way to use virtual methods to perform the type-specific action.






      share|improve this answer


























        0












        0








        0







        Using switch with GetType is the wrong way to implement polymorphism, because it only checks the most-derived class (breaks extensibility).



        In your particular case, where you want the Manager to be responsible for the behavior, you might use the dynamic keyword and overloaded methods. But this will again violate SOLID, because it isn't open for extension.



        Instead of violating SOLID this way, try to find a way to use virtual methods to perform the type-specific action.






        share|improve this answer













        Using switch with GetType is the wrong way to implement polymorphism, because it only checks the most-derived class (breaks extensibility).



        In your particular case, where you want the Manager to be responsible for the behavior, you might use the dynamic keyword and overloaded methods. But this will again violate SOLID, because it isn't open for extension.



        Instead of violating SOLID this way, try to find a way to use virtual methods to perform the type-specific action.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered May 3 '12 at 13:54









        Ben VoigtBen Voigt

        235k29311571




        235k29311571






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f10432352%2fc-sharp-add-const-field-using-attributes%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            Academy of Television Arts & Sciences

            L'Équipe

            1995 France bombings