Add [Serializable] attribute to C# output code

I want to use the XmlSerializer or DataContract serializer in C#. These rely on reflection and attributes with which their targets are marked. How can I add custom attributes in C#, such as [Serializable] or, even more importantly, attributes that have arguments, such as:

[DataContract(Name = "SomeArgument", Namespace = "http://www.somewebsite.io")]

Hi!
There is @:strict which is used to declare a native C# attribute.

Example:

import cs.system.AttributeTargets;
import cs.system.AttributeUsageAttribute;
import cs.system.Attribute;

final class Main {
	@:strict(DataContract({Name:"SomeArgument", Namespace: "http://www.somewebsite.io"}))
	static function main() {
	}
}

@:nativeGen
@:strict(AttributeUsageAttribute(AttributeTargets.Method))
class DataContract extends Attribute {
	@:property
	public var Name:String;

	@:property
	public var Namespace:String;

	public function new() {
		super();
	}
}

Which will generate the following c# code:

	[DataContract(Name = "SomeArgument", Namespace = "http://www.somewebsite.io")]
	public static void main() {
	}

I hope it helps.

1 Like

Sorry for bump on super old topic, but this thread is the only resource on adding native attributes in C#, so I just wanted to add if you’re having trouble using @:strict because of the type-checker, you can also just use @:meta, which will add the provided string directly to an attribute in C#.

Literally just discovered this metadata, and it’s saved my life. I was writing some classes in separate C# files just because it was impossible to make the Haxe compiler accept that my attributes existed.

Example:

@:nativeGen
@:meta(DataContract(Name="SomeArgument", Namespace="http://www.somewebsite.io"))
class MyClass {
	function main() {
	}
}

Will generate:

[DataContract(Name="SomeArgument", Namespace="http://www.somewebsite.io")]
class MyClass {
	void main() {
	}
}