Search⌘ K
AI Features

Solution: Content Age Restriction

Explore how to create and apply a custom AgeRestrictedAttribute in C# to control access based on user age. Understand how to define attribute usage, assign minimum age properties, and use reflection to dynamically check these restrictions at runtime.

We'll cover the following...
C# 14.0
using System.Reflection;
using SocialPlatform;
var news = new NewsPost { Headline = "Local weather update" };
var graphic = new GraphicPost { Content = "Sensitive content here" };
Console.WriteLine($"16-year-old viewing News: {CanUserViewPost(news, 16)}");
Console.WriteLine($"16-year-old viewing Graphic Post: {CanUserViewPost(graphic, 16)}");
Console.WriteLine($"21-year-old viewing Graphic Post: {CanUserViewPost(graphic, 21)}");
static bool CanUserViewPost(object post, int userAge)
{
Type type = post.GetType();
var attribute = type.GetCustomAttribute<AgeRestrictedAttribute>();
if (attribute != null)
{
return userAge >= attribute.MinimumAge;
}
return true;
}
...