I'm creating a custom class in c# and I want to add a method in a property
So, a custom method in a property for example it's like the ToString method. But I want to create a new one in a property with attributes
(like this:
using System;
namespace foo.Example
{
public class foo
{
object object = new object();
string test = object.Something(); //Like ToString()
}
}
but the ToString() method in any objects like classes, methods, properties, etc). I want to add a method into a property like what I said above with the object with the .ToString() method in a property and anything.
I actually tried this: How to create a custom attribute in C# but it doesn't work, I tried everything but there are not many examples in Google and some are outdated.
I tried this (I want to add ToInt method, ToDouble (It's more efficient)):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Winforms.Something.Attributes
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class PropertyToValueAttribute : Attribute
{
public PropertyToValueAttribute() { }
public int ToInt()
{
object value = 0;
Type type = this.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(type.GetProperties());
foreach (PropertyInfo prop in props)
{
value = prop.GetValue(this, null);
}
return Convert.ToInt32(value);
}
public double ToDouble()
{
object value = 0;
Type type = this.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(type.GetProperties());
foreach (PropertyInfo prop in props)
{
value = prop.GetValue(this, null);
}
return Convert.ToDouble(value);
}
}
}
I did that in the class where I want to use the property:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Winforms.Something.Attributes;
namespace Winforms.Something
{
[Serializable]
public class AttributedClass
{
private double _propexample;
[PropertyToValue]
public double Property
{
get { return _propexample; }
set { _propexample = value; }
}
Thanks for your help