Why can't find [DataContract] and [DataMember] Attributes in C#?

I have this code snippet in C# and WPF

using System;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;

namespace DeskApp2_0.Core
    public class Common
        [DataContract] /* This [DataContract] is highlighted as not found. */
        public struct SystemData
            [DataMember] /* This [DataMember] is highlighted as not found. */
            public byte Version;
            [DataMember] /* This one as well. */
            public ushort Name;

This is the screenshot of the Error

Any help appreciated.


In order to be able to use the [DataContract] and [DataMember] attributes you’re going to need to:

  1. using System.Runtime.Serialization;
    That using is critical. But apparently you’ve added it to your file according to the code snippet you provided.

  2. Make sure you are targeting .Net Framework version 4.0+ and above.

  3. Add the “System.Runtime.Serialization” reference to your project.
    Follow these steps:

  4. Add a new reference on your solution explorer:
    visual studio - solution explorer - add reference

  5. Past this System.Runtime.Serialization into the search box:
    visual studio - add reference - search box

  6. Check the appropriate reference.
    visual studio - references - System.Runtime.Serialization

  7. Press OK and you’re done.
    visual studio - references - ok

  8. Sometimes even if you follow the steps above, Visual Studio might fail to compile the [DataContract] and [DataMember] attributes. What you can do in that case is:

  9. Rebuild the entire solution (clean and then build).

  10. Reload the project.

  11. Close and reopen the Solution.

  12. Restart Visual Studio.

  13. If you are still facing some issue, then probably better to start a new topic and reference this topic. With the specifics of your issue.

1 Like

Well… Visual Studio, has been quite verbose and explained why it’s highlighting your [DataContract] and [DataMember] attributes.

Read the error again:

The type or namespace name ‘DataContract’ could not be found (are you missing a using directive or an assembly reference?)

As you can see Visual Studio, is assuming that there are two possible reasons for that issue:

  1. missing a using directive
    As @isoftech mentioned, you should add the using System.Runtime.Serialization; and it seems like you’ve done that already.

  2. an assembly reference
    As @isoftech explains again on point #3 on his post, You should be adding the System.Runtime.Serialization reference to your project references. follow his tips.

That’s all you need to do.