Performance Enum vs class? - vb.net

i found few new style (for me) to "define" output from select query.
Private Enum Item
ID
Item
Description
End Enum
Private Class Item
Private ID as String
Private Item as String
Private Desc as String
End Class
I 'm thinking of using either one of them. by using class i does not need to re-cast the element type before i display. but Enum seems like easier to understand.
Anyone have some suggestion how to decide?

Enum members are numeric (usually integer, but can be long). But they are not variable and do not change at runtime. So your enum equates to:
Private Enum Item
ID = 0
Item = 1
Description = 2
End Enum
If you want Description to be a string, then a class is a better idea. Enums are used to reference or index something or limit/define a selection. Like:
Public Property Stooge As Stooges
Friend Enum Stooges
Larry
Moe
Curly
Shemp
CurlyJoe
End Enum
The Stooge Property must be one of those values. in code it will show you the text ("moe") but store and integer (1). users will be shown the text in drop downs etc.
You can associate a description with Enum constants:
Public Enum Stooges
<Description("Larry - Funny one")> Larry
<Description("Moe - 'Smart' One")> Moe
<Description("Curly - Sore One")> Curly
<Description("Shemp - One with bad haircut")> Shemp
<Description("CurlyJoe - Last one")> CurlyJoe
End Enum
To get the description for a single one:
Public Shared Function GetDescription(ByVal EnumConstant As [Enum]) As String
Dim fi As Reflection.FieldInfo =
EnumConstant.GetType().GetField(EnumConstant.ToString())
Dim attr() As DescriptionAttribute =
DirectCast(fi.GetCustomAttributes(GetType(DescriptionAttribute),
False), DescriptionAttribute())
If attr.Length > 0 Then
Return attr(0).Description
Else
Return EnumConstant.ToString() ' return enum name if no Descr
End If
End Function
Usage: str = enumHelper.GetDescription(Stooge.Moe) (enumHelper is the name of the calss where the static/shared function resides).
To get a String Array of all the descriptions:
Public Shared Function GetDescriptions(ByVal type As Type) As String()
Dim n As Integer = 0
Dim enumValues As Array
Try
enumValues = [Enum].GetValues(type)
Dim Descr(enumValues.Length - 1) As String
For Each value As [Enum] In enumValues
Descr(n) = GetDescription(value)
n += 1
Next
Return Descr
Catch ex As Exception
MessageBox.Show(ex.Message)
Return Nothing
End Try
End Function
Usage: Dim strEnum As String() = enumHelper.GetDescriptions(GetType(Stooges))

From your question, what you really mean is Struct vs Class. I would default to creating a class. The main reason to use a struct vs a class, is when you need value semantics -- assignment/parameters copies the bits, not a pointer. This is fairly rare in my experience. Unless you have a compelling reason (and you know the difference), go with a class.

Related

How to find the index of an object in a list of objects? VB.Net

I am creating a method FindPerson which searches for a given name in a list of objects and returns the index in the list of the object with this name if found, otherwise it returns -1.
Public Class TPerson
Private Name As String
Private Address As String
Private Age As Integer
Public Sub New()
Name = "x"
Address = "x"
Age = 0
End Sub
……
End Class
Public Class TGroup
Private Group As List(Of TPerson)
Private GroupSize As Integer
Public Sub New(size As Integer)
GroupSize = size
Group = New List(Of TPerson)
End Sub
Public Sub FindPerson(findname As String)
Dim index As Integer
index = Group.FindIndex(findname) 'error
End Sub
End Class
The output should be an index in the list, however when I run the program I get the error: BC30311 Value of type 'String' cannot be converted to 'Predicate(Of TPerson)'
I am not quite sure how to fix this any help will be appreciated
How exactly do you expect the FindIndex method to know what to do with that String that you are passing in? You seem to assume that it will know that it represents a name and that it needs to match an item by Name property but how do you think it's going to do that? Why do you think it would match on Name rather than Address?
As the error message says, you need to provide a Predicate which is a delegate that takes an object of type T and returns a Boolean. In your case, T is TPerson and the Boolean needs to indicate whether findname matches its Name property. The simplest way to do that is with a Lambda expression:
Dim index = Group.FindIndex(Function(person) person.Name = findname)
You could do it with a named method and a delegate if you wanted to but it would be more long-winded and it would mean getting the findname value in by some convoluted means. If you read the documentation for the FindIndex method (which you should have done before posting here) you can find an example of that sort of thing.

VBA List of Custom Datastructures

One of the main problems in VBA are custom data structures and lists.
I have a loop which generates with each iteration multiple values.
So as an example:
Each loop iteration generates a string "name" an integer "price" and an integer "value".
In C# for example I'd create a class which can hold these three values and with each loop iteration I add the class object to a list.
How can I do the same thing in VBA if I want to store multiple sets of data when not knowing how many iterations the loop will have (I cant create an array with a fixed size)
Any ideas?
The approach I use very frequently is to use a class and a collection. I also tend to use an interface model to make things more flexible. An example would look something like this:
Class Module IFoo
Option Explicit
Public Sub Create(ByVal Name as String, ByVal ID as String)
End Property
Public Property Get Name() as String
End Property
Public Property Get ID() as String
End Property
This enforces the pattern I want for my Foo class.
Class Module Foo
Option Explicit
Private Type TFoo
Name as String
ID as String
End Type
Private this as TFoo
Implements IFoo
Private Sub IFoo_Create(ByVal Name as String, ByVal ID as String)
this.Name = Name
this.ID = Name
End Sub
Private Property Get IFoo_Name() as String
IFoo_Name = this.Name
End Property
Private Property Get IFoo_ID() as String
IFoo_ID = this.ID
End Property
We get intellisense from the Private Type TFoo : Private this as TFoo where the former defines the properties of our container, the latter exposes them privately. The Implements IFoo allows us to selectively expose properties. This also allows you to iterate a Collection using an IFoo instead of a Foo. Sounds pointless until you have an Employee and a Manager where IFoo_BaseRate changes depending on employee type.
Then in practice, we have something like this:
Code Module Bar
Public Sub CollectFoo()
Dim AllTheFoos as Collection
Set AllTheFoos = New Collection
While SomeCondition
Dim Foo as IFoo
Set Foo = New Foo
Foo.Create(Name, ID)
AllTheFoos.Add Foo
Loop
For each Foo in AllTheFoos
Debug.Print Foo.Name, Foo.ID
Next
End Sub
While the pattern is super simple once you learn it, you'll find that it is incredibly powerful and scalable if implemented properly. It also can dramatically reduce the amount of copypasta that exists within your code (and thus reduce debug time).
You can use classes in VBA as well as in C#: Class Module Step by Step or A Quick Guide to the VBA Class Module
And to to the problem with the array: you can create an array with dynamic size like this
'Method 1 : Using Dim
Dim arr1() 'Without Size
'somewhere later -> increase a size to 1
redim arr1(UBound(arr1) + 1)
You could create a class - but if all you want to do is hold three bits of data together, I would define a Type structure. It needs to be defines at the top of an ordinary module, after option explicit and before any subs
Type MyType
Name As String
Price As Integer
Value As Integer
End Type
And then to use it
Sub test()
Dim t As MyType
t.Name = "fred"
t.Price = 12
t.Value = 3
End Sub

How To Iterate Over Members of a Structure Array in VB.net Using Member Function

I have a vb.net enumeration that looks like this:
' define enumeration for keypad states
Enum KeyPadState
KEYPAD_NO ' no keypad
KEYPAD_UC ' upper case keypad
KEYPAD_LC ' lower case keypad
KEYPAD_NU ' numeric keypad
KEYPAD_SY ' symbol keypad
End Enum
I then defined a structure element to be used to translate the members of the above enumeration from enumeration values to string values and back again. The declared structure looks like below. Note the member functions that I have tried to insert. The "New" one is working.
' define keypad type look up structure
Private Structure KeyPadXlat
Dim KeyPadEnum As KeyPadState
Dim KeyPadStr As String
' initializer subroutine
Public Sub New(nKeyPadEnum As KeyPadState, nKeyPadStr As String)
KeyPadEnum = nKeyPadEnum
KeyPadStr = nKeyPadStr
End Sub
' translate string to enum
Public Function ToEnum(xKeyPadStr As String) As KeyPadState
For Each item As KeyPadXlat In ????
Next
End Function
' translate enum to string
Public Function ToStr(xKeyPadEnum As KeyPadState) As String
End Function
End Structure
The actual instance of the structure array is shown below with its initializer code.
Dim KeyPadLookUp() As KeyPadXlat = { _
New KeyPadXlat(KeyPadState.KEYPAD_NO, "KEYPAD_NO"), _
New KeyPadXlat(KeyPadState.KEYPAD_UC, "KEYPAD_UC"), _
New KeyPadXlat(KeyPadState.KEYPAD_LC, "KEYPAD_LC"), _
New KeyPadXlat(KeyPadState.KEYPAD_NU, "KEYPAD_NU"), _
New KeyPadXlat(KeyPadState.KEYPAD_SY, "KEYPAD_SY") _
}
So my question is with regard to the member functions I am trying to create to translate back and forth between the enumeration value and the string value. I have copied one of them here again for reference:
' translate string to enum
Public Function ToEnum(xKeyPadStr As String) As KeyPadState
For Each item As KeyPadXlat In ????
Next
End Function
What I need help with is how to write the code for the For Each loop so that it iterates across all of the elements of the structure array when being in a member function.
To be honest, you really don't need all that code. This should do it nicely.
Enum KeyPadState
KEYPAD_NO ' no keypad
KEYPAD_UC ' upper case keypad
KEYPAD_LC ' lower case keypad
KEYPAD_NU ' numeric keypad
KEYPAD_SY ' symbol keypad
End Enum
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim state As KeyPadState
state = KeyPadState.KEYPAD_LC
'this line will assign the name of the enum `state` to a string called `tempstring`
'It's hardly worth encapsulating it into a function so I've left it as is
'But if you want to provide consistent code, it would be better to.
Dim tempstring As String
tempstring = [Enum].GetName(GetType(KeyPadState), state)
Dim anyString As String = "KEYPAD_UC"
Dim tempState As KeyPadState
'the following line will try to parse `anyString` to an enum value of the same type as the variable to be assigned.
'In this case `state`
tempState = ParseToKeypadState(anyString)
End Sub
Private Function ParseToKeypadState(tempString As String) As KeyPadState
Dim returnValue As KeyPadState
If Not [Enum].TryParse(tempString, returnValue) Then
'handle parsing error here
End If
Return returnValue
End Function
There's all sorts wrong with your code there.
Firstly, I'd suggest that your naming conventions are poor. If you do as is done throughout the .NET Framework then you enumeration would look like this:
Enum KeyPadState
None
UpperCase
LowerCase
Numeric
Symbol
End Enum
That's clear and self-documenting.
Secondly, it is not recommended to use abbreviations like "Xlat". That's meaningless to anyone without prior knowledge. Is it so onerous to write "Translate" and then let Intellisense find it whenever you need to use it in code?
As for the implementation of your class, why does it need any methods at all? You are passing in the KeyPadState value and the text representation when you create an instance so what is there for those methods to do? Your structure should simply be a constructor and two properties:
Private Structure KeyPadStateTranslation
Public ReadOnly Property Value As KeyPadState
Public ReadOnly Property Text As String
Public Sub New(value As KeyPadState, text As String)
Me.Value = value
Me.Text = text
End Sub
End Structure
The property values are set when the instance is created and they are retrieved via the properties. Everything also has an appropriate name.
That said, you don't even need to provide the text because you can simply call ToString on the value to get it:
Private Structure KeyPadStateTranslation
Public ReadOnly Property Value As KeyPadState
Public ReadOnly Property Text As String
Public Sub New(value As KeyPadState)
Me.Value = value
Me.Text = value.ToString()
End Sub
End Structure
Also, the fact that that structure is declared Private is an issue. That indicates that it is declared inside another type. That's not right. Structures are first-class types, just like classes, so they belong in their own dedicated code file, just like classes.
What's the point of that structure at all though? You'd still have to loop through your array to find an instance that matches either a value or some text so it doesn't really help. A Dictionary might be better but you may as well just call ToString on a value if you need to convert that way and use Enum.Parse or .TryParse when you need to go the other way.

Passing Enum Array or list to Function

I want to compare an enum array to single enum instance.
Introduction
I have a class with an enum type array\list
Public Enum InvalidEmailType
Multiple_Updates
Period_Before_At_Sign
Missing_Dot_Com
End Enum
Public Class CustomerClass
Public CustomerName As String
Public ErrorTypeList = [Enum].GetValues(GetType(InvalidEmailType))
Public ErrorDescription As String
End Class
Depending on what values are added to the list, I want to run specific code.
In order to do this I compare the entire list to a single instance:
If UpdateCustomer.MatchErrorType(customer.ErrorTypeList, InvalidEmailType.Trailing_Period) = True Then
'Run Code
End If
Inside the function I compare the entire list against the single instance.
In other words, I loop through the entire list inside the class and check if the value is there:
Public Shared Function MatchErrorType(CustomerErrortypeList As List(Of InvalidEmailType), EmailError As InvalidEmailType) As Boolean
MatchErrorType = False
Dim Found As InvalidEmailType = CustomerErrortypeList.Where(Function(match) match.ToString = EmailError.ToString).OrderByDescending(Function(match) match.ToString).FirstOrDefault()
If Found > 0 Then
MatchErrorType = True
End If
End Function
Here is the problem:
How do I declare the array\list in the function parameters?
List(Of InvalidEmailType) does not work, as I get a cast error
Unable to cast object of type 'EmailValidationReport.InvalidEmailType[]' to type 'System.Collections.Generic.List`1[EmailValidationReport.InvalidEmailType]'
Set ErrorTypeList to a List(of InvalidEmailType) instead of array.
Public ErrorTypeList = [Enum].GetValues(GetType(InvalidEmailType)) _
.Cast(of InvalidEmailType)().ToList()
or
Dim list = customer.ErrorTypeList.Cast(of InvalidEmailType)().ToList()
If UpdateCustomer.MatchErrorType(list, InvalidEmailType.Trailing_Period) Then
'Run Code
End If
Since you aren't doing anything that is specific to List or Array, you can make your method signature take in an IEnumerable instead of a List. This should be able to handle both List and Array (and a few more types as well).
Public Shared Function MatchErrorType(CustomerErrortypeList As IEnumerable(Of InvalidEmailType), EmailError As InvalidEmailType) As Boolean
Dim Found As InvalidEmailType = CustomerErrortypeList.Where(Function(match) match.ToString = EmailError.ToString).OrderByDescending(Function(match) match.ToString).FirstOrDefault()
MatchErrorType = (Found > 0)
End Function

Define String ENUM in VB.Net

I am using Window Application for my project. There is situation where i need to define string enum and using it in my project.
i.e.
Dim PersonalInfo As String = "Personal Info"
Dim Contanct As String = "Personal Contanct"
Public Enum Test
PersonalInfo
Contanct
End Enum
Now i want value of that variable PersonalInfo and Contract as "Personal Info" and "Personal Contanct".
How can i get this value using ENUM? or anyother way to do it.
Thanks in advance...
For non-integer values, Const in a Structure (or Class) can be used instead:
Structure Test
Const PersonalInfo = "Personal Info"
Const Contanct = "Personal Contanct"
End Structure
or in a Module for direct access without the Test. part:
Module Test
Public Const PersonalInfo = "Personal Info"
Public Const Contanct = "Personal Contanct"
End Module
In some cases, the variable name can be used as a value:
Enum Test
Personal_Info
Personal_Contanct
End Enum
Dim PersonalInfo As String = Test.Personal_Info.ToString.Replace("_"c, " "c)
' or in Visual Studio 2015 and newer:
Dim Contanct As String = NameOf(Test.Personal_Contanct).Replace("_"c, " "c)
You could just create a new type
''' <completionlist cref="Test"/>
Class Test
Private Key As String
Public Shared ReadOnly Contact As Test = New Test("Personal Contanct")
Public Shared ReadOnly PersonalInfo As Test = New Test("Personal Info")
Private Sub New(key as String)
Me.Key = key
End Sub
Public Overrides Function ToString() As String
Return Me.Key
End Function
End Class
and when you use it, it kinda looks like an enum:
Sub Main
DoSomething(Test.Contact)
DoSomething(Test.PersonalInfo)
End Sub
Sub DoSomething(test As Test)
Console.WriteLine(test.ToString())
End Sub
output:
Personal Contanct
Personal Info
How about using Tagging. Something like:
Public Enum MyEnum
<StringValue("Personal Contact")>Contact
<StringValue("My PersonalInfo")>PersonalInfo
End Enum
You would have to write the StringValue attribute as:
Public Class StringValueAttribute
Inherits Attribute
Public Property Value As String
Public Sub New(ByVal val As String)
Value = val
End Sub
End Class
To get it out:
Public Function GetEnumByStringValueAttribute(value As String, enumType As Type) As Object
For Each val As [Enum] In [Enum].GetValues(enumType)
Dim fi As FieldInfo = enumType.GetField(val.ToString())
Dim attributes As StringValueAttribute() = DirectCast(fi.GetCustomAttributes(GetType(StringValueAttribute), False), StringValueAttribute())
Dim attr As StringValueAttribute = attributes(0)
If attr.Value = value Then
Return val
End If
Next
Throw New ArgumentException("The value '" & value & "' is not supported.")
End Function
Public Function GetEnumByStringValueAttribute(Of YourEnumType)(value As String) As YourEnumType
Return CType(GetEnumByStringValueAttribute(value, GetType(YourEnumType)), YourEnumType)
End Function
And then a call to get the Enum (using string attribute):
Dim mEnum as MyEnum = GetEnumByStringValueAttribute(Of MyEnum)("Personal Contact")
To get the "Attribute" value out (removed handling 'Nothing' for clarity):
Public Function GetEnumValue(Of YourEnumType)(p As YourEnumType) As String
Return DirectCast(Attribute.GetCustomAttribute(ForValue(p), GetType(StringValueAttribute)), StringValueAttribute).Value
End Function
Private Function ForValue(Of YourEnumType)(p As YourEnumType) As MemberInfo
Return GetType(YourEnumType).GetField([Enum].GetName(GetType(YourEnumType), p))
End Function
And the call to get the string attribute (using Enum):
Dim strValue as String = GetEnumValue(Of MyEnum)(MyEnum.Contact)
How can i get this value using ENUM? or anyother way to do it.
There are three common ways of mapping enum values to strings:
Use a Dictionary(Of YourEnumType, String)
Decorate the enum values with attributes (e.g. DescriptionAttribute) and fetch them with reflection
Use a Switch statement
The first of these options is probably the simplest, in my view.
I know this is an old post put I found a nice solution that worth sharing:
''' <summary>
''' Gives acces to strings paths that are used often in the application
''' </summary>
Public NotInheritable Class Link
Public Const lrAutoSpeed As String = "scVirtualMaster<.lrAutoSpeed>"
Public Const eSimpleStatus As String = "scMachineControl<.eSimpleStatus>"
Public Const xLivebitHMI As String = "scMachineControl<.xLivebitHMI>"
Public Const xChangeCycleActive As String = "scMachineControl<.xChangeCycleActive>"
End Class
Usage:
'Can be anywhere in you applicaiton:
Link.xChangeCycleActive
This prevents unwanted extra coding, it's easy to maintain and I think this minimizes extra processor overhead.
Also visual studio shows the string attributes right after you type "Link"
just like if it is a regular Enum
If all you want to do is display the enums in a list or combo, you can use tagging such as
Private Enum MyEnum
Select_an_option___
__ACCOUNTS__
Invoices0
Review_Invoice
__MEETINGS__
Scheduled_Meetings0
Open_Meeting
Cancelled_Meetings0
Current_Meetings0
End Enum
Then pull the MyEnum into a string and use Replace (or Regex) to replace the tags: "___" with "...", "__" with "**", "_" with " ", and remove trailing numbers. Then repack it up into an array and dump it into a combobox which will look like:
Select an option...
**ACCOUNTS**
Invoices
Review Invoice
**MEETINGS**
Scheduled Meetings
Open Meeting
Cancelled Meetings
Current Meetings
(You can use the numbers to, say, disable a text field for inputting an invoice number or meeting room. In the example, Review Invoice and Open Meeting might be expecting additional input so a text box might be enabled for those selections.)
When you parse the selected combo item, the enumeration will work as expected but you only really need to add a single line of code - the text replacement - to get the combo to look as you wish.
(The explanation is about 10 times as involved as the actual solution!)
This technique from Microsoft - "How to: Determine the String Associated with an Enumeration Value (Visual Basic)" - will be useful in some situations (it didn't help with mine unfortunately though :( ). Microsoft's example:
VB:
Public Enum flavorEnum
salty
sweet
sour
bitter
End Enum
Private Sub TestMethod()
MsgBox("The strings in the flavorEnum are:")
Dim i As String
For Each i In [Enum].GetNames(GetType(flavorEnum))
MsgBox(i)
Next
End Sub