Search code examples
c#asp.netsecurityxml-deserialization

.NET Serialization getters and setters


I want to try a .NET deserialization example, but it seems I am not able to get the getters and setters working. This is my code

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace WindowsFormsApplication3

{
    [XmlRoot]
    public class TestClass
    {
        public string classname;
        private string name;
        private int age;
        [XmlAttribute]
        public string Classname { get => classname; set => classname = value; }
        [XmlElement]
        public string Name { get => name; set => name = value; }
        [XmlElement]
        public int Age { get=>age; set => age = value; }
        public override string ToString()
        {
            return base.ToString();
        }

    }

    class Program
    {
        static void Main(string[] args)
        {
            TestClass testClass = new TestClass();
            testClass.Classname = "test";
            testClass.Name = "william";
            testClass.Age = 50;
            Console.WriteLine("Hello World!");
            MessageBox.Show("Test");

        }
    }
}

And I get the following error in the get declaration: Not all code paths return a value

enter image description here


Solution

  • As commented by @CodeCaster, you need a minimum of C# 7.0 to work around on Expression-Bodied Members and your visual studio doesn't support it.

    So you can upgrade your visual studio to C# 7.0 or use below with current version,

    You can use

    public string Classname
    {
        get { return classname; }
        set { classname = value; }
    }
    

    instead of

    public string Classname
    {
        get => classname;
        set => classname = value;
    }
    

    And do the same for all other remaining properties in your class those are with expression-bodies.