I would like to throw an exception during compilation time if the given parameter in the IMarkupExtension is not compatible with the type expected by me. Can I achieve this effect?
Below I put my experiments, but I do not know where and how to check what I wrote in "TODO"
Code (I marked todo)
using System;
using Xamarin.Forms.Xaml;
namespace MySample
{
public class SampleClass : IMarkupExtension
{
public IParameter Parameter { get; set; }
public object ProvideValue(IServiceProvider serviceProvider)
{
return Parameter.GetData();//TODO: throw Exception("Parameter must be of type SampleData1")
}
}
public interface IParameter
{
string GetData();
}
public class SampleData1 : IParameter
{
public string GetData()
{
return "Data1";
}
}
public class SampleData2 : IParameter
{
public string GetData()
{
return "Data2";
}
}
}
XAML
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:mysample="clr-namespace:MySample"
x:Class="MySample.SamplePage">
<ContentPage.Resources>
<mysample:SampleData2 x:Key="SampleData2" />
</ContentPage.Resources>
<ContentPage.Content>
<StackLayout>
<Label>
<Label.Text>
<mysample:SampleClass Parameter="{StaticResource SampleData2}" />
</Label.Text>
</Label>
</StackLayout>
</ContentPage.Content>
</ContentPage>
Please note that the parameter is of the SampleData2 type, but I want to throw an exception if it is not of the SampleData1 type.
Resource
<mysample:SampleData2 x:Key="SampleData2" />
Resource usage
Parameter="{StaticResource SampleData2}"
Check (not necessarily in this place, but definitely during compilation)
public object ProvideValue(IServiceProvider serviceProvider)
{
return Parameter.GetData();//TODO: throw Exception("Parameter must be of type SampleData1")
}
I think it is not possible to throw exception at compile time. The logical errors cannot be detected by the compiler, and hence they are detected only when the program is executed.
Compile time error:
If we do not follow the proper syntax and semantics of any programming language then the compiler throw compile time error.
For example:
1.Missing semicolon
2.writing keywords in uppercase
3.varaiable not defiend etc
Runtime error:
A runtime error is generated when the program is in running state. They are often termed as an exception.
For example:
1.Division by zero
2.Running out of memory
3.Dereferencing null pointer etc
You can use code below to
throw a Exception
when this function triggered andParameter
is not of theSampleData1
type.