Skip to content

Instantly share code, notes, and snippets.

@savaged
Last active August 16, 2019 16:10
Show Gist options
  • Save savaged/f973aebc6cefb9b134f8ee6a57aa2af4 to your computer and use it in GitHub Desktop.
Save savaged/f973aebc6cefb9b134f8ee6a57aa2af4 to your computer and use it in GitHub Desktop.
Just a quick referencce on defining and using a custom bool like Attribute
using System;
using System.Collections.Generic;
using System.Linq;
namespace Savaged.Sandpit
{
class Program
{
static void Main(string[] args)
{
var models = new List<IBaseModel>
{
new FirstModel(),
new SecondModel()
};
foreach (var model in models)
{
var attribs = model.GetType()
.GetCustomAttributes(typeof(AtomicAttribute), true);
bool isAtomic = attribs.FirstOrDefault()
is AtomicAttribute attrib
? (bool)attrib : false;
Console.WriteLine($"{model.GetType().Name} {Convert(isAtomic)} atomic");
}
Console.ReadLine();
}
static string Convert(bool value)
{
return value ? "is" : "is not";
}
}
public class AtomicAttribute : Attribute
{
public AtomicAttribute()
{
Value = true;
}
public bool Value { get; }
public static implicit operator bool(AtomicAttribute value)
{
if (value is null)
{
return false;
}
return value.Value;
}
public static explicit operator AtomicAttribute(bool value)
{
if (!value)
{
return null;
}
return new AtomicAttribute();
}
}
public interface IBaseModel
{
string Name { get; set; }
}
public abstract class BaseModel : IBaseModel
{
public string Name { get; set; }
}
public class FirstModel : BaseModel
{
}
[Atomic]
public class SecondModel : BaseModel
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment