Custom Attribute trouble

R

Rowan

Hello,

I've been dinking around with using Custom Attributes at the
encouragement of an answer to a previous post and found it pretty easy
to create and set them. But now I am having a lot of trouble figuring
out how to get the values out. I think I am overcomplicating it. (I am
going to leave the terribly awful code I am messing with out.)

I have the following:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class fooFieldAttribute : System.Attribute
{
public int RequiredLength { get; set; }
public bool LeadingZeros { get; set; }
public fooFieldAttribute()
{
}
}


public class fooHeader
{
private string _HeaderIdentifier = "H1"
[fooField(RequiredLength = 2, LeadingZeros = false)]
public string HeaderIdentifier
{
get { return _HeaderIdentifier ; }
}

private string _Count = "1"
[fooField(RequiredLength = 3, LeadingZeros = true)]
public string Count
{
get { return _Count ; }
}


private string FormatWithPadding(string str, int reqlength, bool
leadingzeros)
{
bool useDefault = string.IsNullOrEmpty(str);

Int32 i = reqlength - str.Trim().Length;
if (leadingzeros && !useDefault)
{
return str.Trim().PadLeft(i, '0');
}
else
{
return str.Trim().PadRight(i, ' ');
}
}

Now I want to do something like:

public void Write(fooHeader fooheader)
{
StringBuilder strHeader = new StringBuilder();
strHeader.Append = FormatWithPadding(fooHeader.HeaderIdentifier,
fooFieldAttribute.RequiredLength for HeaderIdentifier,
fooFieldAttribute.LeadingZeros for HeaderIdentifier);
strHeader.Append = FormatWithPadding(fooHeader.Count,
fooFieldAttribute.RequiredLength for Count,
fooFieldAttribute.LeadingZeros for Count);

Can anyone help?



}
 
R

Rowan

Thanks...this has been a very big help. I am having a little trouble
with a cast and am unsure what to do.

When I try to return rgobj[0]; I get the error
Cannot implicitly convert type 'object' to ...fooFieldAttribute'. An
explicit conversion exists (are you missing a cast?)

Is there something easy I am overlooking? I've tried quite a few
variations with no luck.
 
R

Rowan

Actually, I think I got it...return rgobj[0] as fooFieldAttribute;
works! I appreciate your help...soooo much better than what I was
messing with.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top